Elixir Capture Operator
The capture operator is the & sign, which builds an anonymous function in a short form. Inside the short form, &1 stands for the first argument.
A capture adds one to its argument
The placeholder &1 marks where the argument goes. Calling the captured function with 41 gives 42.
add_one = &(&1 + 1)
IO.puts(add_one.(41))Two placeholders take two arguments
A capture can use &1 and &2 for its two arguments. Adding the two placeholders adds the two passed values.
add = &(&1 + &2)
IO.puts(add.(3, 4))
IO.puts(add.(20, 22))A named function can be captured by name and arity
Writing &String.upcase/1 captures the existing upcase function. The captured value is a function, and the dot call runs it.
cap = &String.upcase/1
IO.puts(cap.("hi"))
IO.puts(is_function(cap))Example
shout = &String.upcase/1
double = &(&1 * 2)
add = &(&1 + &2)
IO.puts(shout.("hello"))
IO.puts(double.(15))
IO.puts(add.(20, 22))Key points
- Capture operator: the & sign that starts a short anonymous function.
- Placeholder: &1 stands for the first argument, and &2 stands for the second argument.
- Short form: &(&1 + 1) builds the same function as fn x -> x + 1 end.
- Arity: the number of arguments a function takes.
- Named capture: &String.upcase/1 captures the named function upcase, and the /1 states its arity.
- Dot call: a captured function is called the same way, with a dot, as in cap.("hi").
In this example, the first line captures the named String.upcase function, and the next two lines build short functions from placeholders. Each captured function is then called with a dot.
Note
in Elixir, the capture form is a shortcut for a simple anonymous function, not a different kind of function.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the function &(&1 * 3) return when it is called with 4?