O'Reilly logo

Programming Elixir by Dave Thomas

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

Comprehensions

When you’re writing functional code, you often map and filter collections of things. To make your life easier (and your code easier to read), Elixir provides a general-purpose shortcut for this: the comprehension.

The idea of a comprehension is fairly simple: given one or more collections, extract all combinations of values from each, optionally filter the values, and then generate a new collection using the values that remain.

The general syntax for comprehensions is deceptively simple:

result = for generator or filter… [, into: value ], do: expression

Let’s see a couple of basic examples before we get into the details.

 
iex>​ ​for​ x <- [ 1, 2, 3, 4, 5 ], ​do​: x * x
 
[1, 4, 9, 16, 25]​​
 
iex>​ ​for​ x <- [ 1, 2, 3, 4, 5 ...

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