O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required