WolframLang: Define Function

By Xah Lee. Date: . Last updated: .
Function[x, body]
represent a function with one parameter.

same as

Function[{x}, body]


x |-> body

Function[{x1, x2 etc}, body]

represent a function (like lisp lambda) with formal parameters x1, x2 etc. When the function is called, body is evaluated, with formal parameters replaced by arguments. For example, Function[{x,y}, x+y][3, 4] return 7. Function

f = Function[ {x,y}, x + y ];
f[3, 4] === 7
(Short syntax: Function[body] is same as ((body)&))

in the body,

  • # or #1 → means first parameter.
  • #2 → means second parameter.
  • #3 → means Third parameter.
  • etc.
  • ## → means rest parameter.
f = Function[ # + #2 ];
f[3, 4] === 7

Formal Parameters Syntax Shortcut

Formal parameters in Function can be represented by #.

# or #1
first parameter.
second parameter.
Third parameter.

e.g. The following are equivalent.

Function[body] has the short syntax body&

e.g. The following are equivalent.

This makes the code even shorter, and is often used.

TIP: it's good idea to add parenthesis like this ((body)&), when using the short form. Because otherwise you run into operator precedence issue that's hard to remember which operator has higher precedence.

Variadic Function, Rest Parameters

## stands for rest parameters in Function's body, useful for define defining function with arbitrary number of parameters.

Represent rest parameters.
Represent rest parameters starting with nth.

e.g. The following are equivalent.

mySum = (Plus[##]&);
mySum[1,2,3] === 6

Map-Arrow Syntax Shortcut

x |-> body
same as Function[x, body]
varList |-> body
same as Function[varList, body]
(x |-> x+1) === Function[ x, x+1 ]

({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 ambiguity.

Named Parameters, Default Values, Polymorphism

If you want function to have named parameters, default values, or polymorphism (meaning, the function behaves differently depending on number of args or their type) , you need to define the function by pattern matching. [see Define Function by Pattern]

TIP: defining function by pattern matching

in Wolfram tutorials, often you'll see defining function with form like this:

f[x_, y_] := body

That works by defining a symbolic expression replacement rule using pattern matching. [see WolframLang: Define Function by Pattern]

WolframLang: Define Function