Function

Function[body]

or body& is a pure (or "anonymous") function. The formal parameters are # (or #1), #2, etc.

Function[x,body]

is a pure function with a single formal parameter x.

Function[{x1,x2,},body]

is a pure function with a list of formal parameters.

Function[params,body,attrs]

is a pure function that is treated as having attributes attrs for purposes of evaluation.

Details

  • When Function[body] or body& is applied to a set of arguments, # (or #1) is replaced by the first argument, #2 by the second, and so on. #0 is replaced by the function itself.
  • If there are more arguments supplied than # i in the function, the remaining arguments are ignored. »
  • ## stands for the sequence of all arguments supplied. »
  • ## n stands for arguments from number n onward. »
  • When applied to an association, #name is equivalent to #["name"], and picks out elements in the association.
  • In the form #name, the characters in name can be any combination of alphanumeric characters not beginning with digits.
  • Function[x,body] can be input as xbody, where the character is entered as fn or \[Function].
  • Function is analogous to λ in LISP or formal logic.
  • Function has attribute HoldAll. The function body is evaluated only after the formal parameters have been replaced by arguments.
  • The named formal parameters xi in Function[{x1,},body] are treated as local, and are renamed xi$ when necessary to avoid confusion with actual arguments supplied to the function. »
  • Function constructs can be nested in any way. Each is treated as a scoping construct, with named inner variables being renamed if necessary. »
  • In Function[params, body, attrs], attrs can be a single attribute or a list of attributes.  »
  • Function[Null,body,attrs] represents a function in which the parameters in body are given using # etc.

Examples

open allclose all

Basic Examples  (4)

Pure function with one parameter:

In[1]:=
Click for copyable input
Out[1]=
In[2]:=
Click for copyable input
Out[2]=
In[3]:=
Click for copyable input
Out[3]=

Pure function with two parameters:

In[1]:=
Click for copyable input
Out[1]=
In[2]:=
Click for copyable input
Out[2]=

Set to be a pure function:

In[1]:=
Click for copyable input
Out[1]=

Use the pure function:

In[2]:=
Click for copyable input
Out[2]=

Pick out named arguments from an association:

In[1]:=
Click for copyable input
Out[1]=

Scope  (15)

Generalizations & Extensions  (4)

Applications  (3)

Properties & Relations  (11)

Possible Issues  (4)

Neat Examples  (2)

See Also

Apply  Construct  Curry  CompiledFunction  InterpolatingFunction  Slot  SlotSequence

Tutorials

Related Workflows

Introduced in 1988
(1.0)
| Updated in 2014
(10.0)