April 2024
Beginner to intermediate
224 pages
5h 7m
English
Anonymous functions are created using the fn keyword. But there’s another technique to create anonymous functions called function capturing. This technique lets you define an anonymous function with a short syntax. It’s very popular when defining a one- or two-line function for use in modules like Enum.
We’ll go over the syntax for function capturing as well as how it can be used on named functions. It’s a quick bit of syntax, so let’s dive right in!
Captured functions begin with the & symbol. Inside the body of the function, &1 is used to refer to the first argument. Here’s an example:
| | $ iex |
| | iex(1)> Enum.map([1, 2, 3], & &1 * 2) |
| | [2, 4, 6] |
The phrase & &1 * 2 is a captured function. It’s ...
Read now
Unlock full access