WolframLang: Function Syntax Shortcut

By Xah Lee. Date: . Last updated: .

Function has many syntax shortcuts.

The following are equivalent:

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.

in the body,

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.

Example: The following are equivalent.

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.

WolframLang: Define Function