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 ], x ...

Get Programming Elixir 1.3 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.