Capture Operator &

The Capture operator, denoted as &, is a unique feature in Elixir that enables the creation of anonymous functions, often in a more succinct and readable way than the traditional fn → end syntax.

The Capture operator is often used to create quick, inline functions. Here’s a simple example:

iex> add = &(&1 + &2)
&:erlang.+/2
iex> add.(1, 2)
3

In the above example, &(&1 + &2) creates an anonymous function that adds two arguments together. The placeholders &1 and &2 refer to the first and second arguments, respectively. The function is then assigned to the variable add, and it can be invoked with add.(1, 2).

When the captured expression is just a direct function call, like &(&1 + &2) which is Kernel./2` applied to its arguments, IEx prints the result as `&:erlang./2, the direct reference to the underlying Erlang function. For anything more involved (see double below), IEx falls back to the generic #Function<…​> representation.

The Capture operator isn’t just for simple functions. It can be used with more complex expressions and even function calls:

iex> double = &(&1 * 2)
#Function<42.113135111/1 in :erl_eval.expr/6>
iex> double.(10)
20

In the above example, &(&1 * 2) creates an anonymous function that doubles its argument.

You can also use the Capture operator to reference named functions from modules. For example, to reference the length function from the List module:

iex> len = &length/1
&:erlang.length/1
iex> len.([1, 2, 3, 4, 5])
5

In the example above, &length/1 captures the length function from the which takes one argument (/1). This function is then assigned to the variable len.