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

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.