ELI5: Elixir Comprehensions

In Elixir the for keyword is used differently than most other language. The for keyword starts something called a comprehension in Elixir.

A comprehension is basically syntactic sugar for looping through enumerables in Elixir.

The first part of the expression, x <- list, is what is known as a generator. They are responsible for “generating” the next value to be called upon by the comprehension. You can have multiple generators, much like you can have nested loops. Comprehension are not just limited to lists. Any enumerable is able to utilize comprehensions.

Comprehensions also have a second piece to them: filters.

Filter example

Here, the second part of the expression, x < 6 describes a condition the bound variable must meet in order to be passed to the block. There can be multiple filters, strung together by commas. Guards are to functions as filters are to comprehensions!

Comprehensions by default return lists. If we wanted our values returned as a different type we would use the :into option. :into can be used with any datatype that is considered a collectable.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store