Pure Functions and Map
Prerequisites: Defining functions
A pure function is a function without a name — written right where you need it.
(#^2 &)[5]
(#1 + #2 &)[3, 4]
Function[x, x^2][5]
(x |-> x^2)[5]
25
7
25
25
- In
#^2 &,#is the argument and&marks the end of the function.#1,#2, ... are the first, second, ... arguments. Function[x, body]andx |-> bodyare the same thing with a named argument — clearer when the body is long.
Map: /@
Map[f, list], written f /@ list, applies f to every element:
f /@ {a, b, c}
#^2 & /@ {1, 2, 3}
StringLength /@ {"kiwi", "apple", "banana"}
{f[a], f[b], f[c]}
{1, 4, 9}
{4, 5, 6}
(For arithmetic, listability does the same: {1, 2, 3}^2. Map works
with any function.)
Select with a pure function
Select[Range[20], # > 15 &]
Select[{"apple", "kiwi", "banana"}, StringLength[#] > 4 &]
SortBy[{"banana", "kiwi", "apple"}, StringLength]
{16, 17, 18, 19, 20}
{apple, banana}
{kiwi, apple, banana}
Apply: @@ and @@@
Apply[f, expr], written f @@ expr, replaces the head:
f @@ {a, b, c}
Plus @@ {1, 2, 3}
Times @@ {2, 3, 4}
f @@@ {{1, 2}, {3, 4}}
f[a, b, c]
6
24
{f[1, 2], f[3, 4]}
Plus @@ {1, 2, 3}turnsList[1, 2, 3]intoPlus[1, 2, 3].@@@applies at level 1 — to each inner list. Useful for lists of pairs:(#1 * #2 &) @@@ {{2, 3}, {4, 5}}gives{6, 20}.
Summary of the shorthand
| Shorthand | Full form | Result |
|---|---|---|
f @ x |
f[x] |
call |
x // f |
f[x] |
call (postfix) |
f /@ {a, b} |
Map[f, {a, b}] |
{f[a], f[b]} |
f @@ {a, b} |
Apply[f, {a, b}] |
f[a, b] |
f @@@ {{a, b}} |
Apply[f, {{a, b}}, {1}] |
{f[a, b]} |
Common mistakes
- Forgetting the
&—#^2 /@ {1, 2}doesn't define a function. - Precedence:
&binds loosely, soSelect[list, # > 2 && # < 5 &]works, but when combining with other operators, parentheses —(# + 1 &) /@ list— keep things clear.
Practice
Given {{"Ada", 36}, {"Alan", 41}}, produce the strings
"Ada is 36" and "Alan is 41".
Show solution
(#1 <> " is " <> ToString[#2] &) @@@ {{"Ada", 36}, {"Alan", 41}}
{Ada is 36, Alan is 41}