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
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)]
Or two separate definitions; one for x_Integer and one for x_Rational
Another interesting example is
Y[x:{_,_}]. In this case, only a two-element list is accepted andxrefers 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.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.
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!
thank you for this! i really appreciate it! Cheers