Wolfram Language Fast Introduction for Programmers
Get Started »

Pure Functions

The Wolfram Language allows what it calls pure functions, indicated by ending with &
Their first argument is indicated by #

(These are also known as anonymous functions, lambda expressions, etc.)

Pure functions work similarly to lambda expressions in Java, but the syntax is simpler and more consistent in the Wolfram Language.

Pure functions work similarly to lambda functions in Python.

Make a pure function for adding 1:

In[1]:=
X
Out[1]=

If a pure function is given as the head of an expression, the function is applied to the arguments:

In[2]:=
X
Out[2]=

Here is a function of several arguments:

In[3]:=
X
Out[3]=

This is an alternative way to specify the function:

In[4]:=
X
Out[4]=

Wolfram Language pure functions provide a much simpler syntax for including multiple parameters than Java lambda expressions.

The second notation for pure functions may be more familiar to a Python programmer in that you need to explicitly name your parameters.

Lots of built-in functions commonly use pure functions:

In[1]:=
X
Out[1]=
In[2]:=
X
Out[2]=
Check Your Understanding

Which of the following is a pure function that adds two numbers?

#1 + #2

Incorrect. A pure function has & at the end.

#1 + # &

Incorrect. The "2" in #2 is needed to specify the second argument. This pure function would be the same as #1 + #1 &.

#1 + #2 &

Correct.

Which of these is the value of (# + 2) & [10]?

# + 2

Incorrect. The value 10 would be substituted for #.

12

Correct.

2

Incorrect. The 10 goes in the place of # and the result is 10 + 2, which is 12.

Which of these is the output of {#2, #1, #3} & [2, 3, 4, 5]?

{2, 1, 3}

Incorrect. These are the slot numbers, not the values of the corresponding arguments.

{3, 2, 4}

Correct.

{3, 2, 4, 5}

Incorrect. The fourth argument, which is 5, is not used in this pure function.