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 ...

Get Programming Elixir 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.