Elixir Comprehensions - Elixir

What are list comprehensions in Elixir?

In Elixir, List comprehensions are syntactic sugar for looping through enumerables. In this chapter we will look at comprehensions for iteration and generation.


In enumerables chapter we came across the map function in the Enum module.

In the above example we're passing a function as the second argument. Each item in the range will be passed into the function and then a new list will be returned containing new values. We looked at this in functions as first class citizens in Elixir.

Mapping, filtering, and transforming are common actions in Elixir. Therefore there is a little different way to acheive the same result as the previous example:

While running the above code, it produces following result:

Second example is a comprehension which is simply a syntactic sugar for what you could achieve by using Enum.map function. However, there are no real benefits of using a comprehension over a function from the Enum module in terms of performance.

Comprehensions are not restricted to lists but can be used with all enumerables.


Filters act as a guard for comprehensions. When a filtered value returns false or nil it will be excluded from the final list. Let’s loop over a range and only worry about even numbers. We are using is_even function from the Integer module to check if a value is even or not.

While running the above code, it produces following result:

Multiple filters can also be used in the same comprehension. Add another filter which you want after is_even filter separated by a comma.

:into Option

In the above example, all the comprehensions returned lists as their result. However, the result of a comprehension can be inserted into different data structures by passing :into option to the comprehension.

For example, it string generator can be used with the :into option to easily remove all spaces in a string:

While running the above code, it produces following result:

Above code removes all spaces from the string using c != ?\s filter and then puts all the returned characters in a string using :into option.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Elixir Topics