Wolfram: Function Syntax Shortcut
Syntax Shortcuts for Function
Function has many syntax shortcuts.
The following are equivalent:
Function[{x,y}, x + y]Function[# + #2]((# + #2) &)({x, y} |-> x + y)
f1 = Function[{x,y}, x + y]; f2 = Function[# + #2]; f3 = ((# + #2) &); f4 = ({x, y} |-> x + y); (* test *) f1[3, 4] === 7 f2[3, 4] === 7 f3[3, 4] === 7 f4[3, 4] === 7
Function Shortcut: Ampersand with Number Sign
Function[body]
is same as
((body)&)
Example: The following are equivalent.
Function[ #1 + #2 ]( #1 + #2 &)
in the body,
#or#1→ means first parameter.#2→ means second parameter.#3→ means third parameter.- etc.
#name→ that picks out value with key name in an Association
#0means the whole function itself. Useful for defining recursive functions.
f = Function[ # + #2 ]; f[3, 4] === 7
💡 TIP:
when using the ampersand shortcut,
it's good idea to add parenthesis, like this
((body)&).
Because otherwise you run into operator precedence issue that's hard to remember which operator has higher precedence.
Rest Parameters (Variadic Function)
## stands for rest parameters in
Function's body,
useful for define defining function with arbitrary number of parameters.
##→ means rest parameters.##1→ means rest parameters starting with first.##2→ means rest parameters starting with second.- etc
Example: The following are equivalent.
Function[{x,y}, {x,y}]({##}&)
mySum = (Plus[##]&); mySum[1,2,3] === 6
Map-Arrow Syntax Shortcut for Function
x |-> body-
same as
Function[x, body](x |-> x+1) === Function[ x, x+1 ] varList |-> body-
same as
Function[varList, body]({x,y} |-> x+y) === Function[ {x,y}, x+y ]
💡 TIP: it's good idea to add parenthesis to the whole
(x |-> x+1).
Because otherwise you run into operator precedence confusion.