F2.06 · part 2 of 3
The capture operator
The capture operator & writes a small anonymous function in one
compact form. Inside &(…), the placeholders &1,
&2, and so on stand for the arguments. It also captures a named function directly,
as &Module.function/arity.
There are two distinct uses sharing the symbol. The first wraps an expression:
&(&1 + 1) is the same function as fn x -> x + 1 end.
The second names an existing function: &String.upcase/1 is the function
String.upcase itself, ready to pass along. Both produce ordinary functions.
Positional placeholders
Wrap an expression in &(…) and use &1 for the
first argument, &2 for the second. The highest placeholder sets the arity. The
result is identical to the matching fn.
Compare each shorthand with its full form.
- capture operator
&— builds a function from an expression or a name.- placeholder
&1,&2… the positional arguments.- function capture
&Module.fun/arity— the named function as a value.- arity
- the number of arguments — set by the highest placeholder.
& form and fn form · same function
Idea
The placeholders are the parameters; the highest one fixes how many there are.
Elixir
One nuance: &(&1) on its own is not allowed — the body must be a call.
The & form is a literal fn with numbered parameters. Reach for it when
the body is a single short expression.
Capturing named functions
The same operator turns a named function into a value. &String.upcase/1 is the
function itself — no wrapper, no placeholders — ready to hand to Enum.map or
store in a variable. The arity says which function of that name.
Pick a captured function and see it applied.
&Module.fun/arity · a named function as a value
F1.07 · higher-order
Capturing names is the tidiest way to pass an existing function as an argument.
Elixir
The /arity is required — it picks among functions sharing a name.
Function capture passes a named function without wrapping it. The arity selects which one.
In the wild
Where you meet & most: as the function argument to Enum.