Anonymous Functions
Elixir has a nice set of built-in modules. One of these, Enum, lets you work on enumerable collections. One of its most commonly used functions is map, which applies a function to a collection, producing a new collection. Let’s fire up the Elixir interactive shell, iex, and try it.
| | iex> Enum.map [2,4,6], fn val -> val * val end |
| | [4,16,36] |
The first argument we pass to map is the collection: in this case, a list of three integers. The second argument is an anonymous function.
Anonymous functions (I’m going to call them fns from now on) are defined between the keywords fn and end. A right-facing arrow, ->, separates a list of zero or more parameters on the left from the body of the function on the right.
We passed
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access