What's the difference between Y[x : _] := 2 * x and Y[x_] := 2 * x when defining a function?

Could someone explain this? I was reading the documentation about Symbolize and patterns, and saw the usage in the form Y[x : _]. What's the difference?

Thanks.

Posted Oct 13, 2019, 3:24 PM UTC

87
Danhec95•

I think (in this case) they are the same. So if you want that x only pass if it has head (for example) 'Integer' you would write:

'Y[x_Integer]' would be the same as 'Y[x:Integer]'

However, If you would accept Integer or Rational then the first form would not apply, then the only way (I think) would be

'Y[x:(Integer | Rational)]

6
beerybeardybear•

Or two separate definitions; one for x_Integer and one for x_Rational

3
selfadjoint•

Another interesting example is Y[x:{_,_}]. In this case, only a two-element list is accepted and x refers to the whole list.

I also used something like F[x:{a_,b_,c_}], which is useful when you want to refer to the whole list and also to the elements of list in the definition.

3
drimago•

hey man this is really interesting. can you paste a link to a documentation page? I can't seem to find it and I am interested in reading more about it.

1
selfadjoint•

You can read more about this in here

https://reference.wolfram.com/language/guide/Patterns.html

and the related tutorials and guides.

There is also an excellent video series by Richard J. Gayloard:

https://www.youtube.com/watch?v=H-rnezxOCA8

He talks about patterns in the first part.

Cheers!

1
drimago•

thank you for this! i really appreciate it! Cheers

1
flying20wedge•

They are the same, but the first notation is necessary if you want to do something more complicated, especially using default arguments; e.g., Y[x:{_,_}:{1,1}]:= .

Just think of the second version as syntactic sugar for when you are doing something simple

2