# Pure Functions

Pure Functions

One-off functions without names.

A pure function performs an operation on an argument. Unlike functions, pure functions don’t have names.

Here’s a pure function that adds one to a number. The expression before the ampersand (&) is the body of the function:

In[]:=

(#+1)&

To use a pure function, put an argument in square brackets after the function. The argument replaces hash signs (#) in the body, in this case giving 2 + 1,

which yields 3:

In[]:=

(#+1)&[2]

Out[]=

3

1.

Pure functions with more than one argument:

You can give pure functions any number of arguments. The first argument is referred to as # or #1, the second argument as #2, and so on.

Here’s a pure function that adds two numbers:

In[]:=

(#1+#2)&[2,3]

Out[]=

5

Here’s a pure function that makes a list of three elements in reverse order:

In[]:=

{#3,#2,#1}&["one","two","three"]

Out[]=

{three,two,one}

2.

Mapping pure functions over lists:

A common use for pure functions is to perform an operation on every element of a list.

Here’s how to rotate every word in a list. The function is “mapped” over the list using the the function (/@):

In[]:=

Rotate[#,45°]&/@{"The","cat","in","the","hat"}

Out[]=

,,,,

The

cat

in

the

hat

3.

Selecting from lists with pure functions:

Another common use for pure functions is selecting elements from lists.

This selects numbers that are greater than 9:

In[]:=

Select[{1,12,8,7,14,15},#>9&]

Out[]=

{12,14,15}

This selects length-2 words:

In[]:=

Select[{"a","am","and","I","in","its"},StringLength[#]2&]

Out[]=

{am,in}