WolframLang: Define Function

By Xah Lee. Date: . Last updated: .
Function[x, body]
same as Function[{x}, body]
Function[{x1, x2 etc}, body]
(Short syntax: Function[{x, y}, x+y] is same as Function[#1+#2] or #1+#2&)
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

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

Variadic Function, Rest Parameters

To write a function with Function for arbitrary number of parameters, use ##.
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]
(aaa |-> bbb) === Function[ aaa, bbb ]

(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]

However, you can define ANY function by using Function. It's not necessary to use pattern matching. If you code a lot WolframLang, it's best to avoid using pattern matching when you can. Because pattern matching is significantly slower, and too much pattern matching makes your function unpredicable.

WolframLang: Define Function

WolframLang in Depth


Comment, Print




Expression, Atom, Head





Data Structure


Pattern Matching


Shell Tasks