Elixir Comprehensions
A comprehension builds a new list by applying an expression to each item of another list. In Elixir it is written with the word for and an arrow that pulls items from the source list.
Each number is squared into a new list
The arrow pulls one number at a time into n. The do expression squares it, and the squares are collected in order.
numbers = [12, 15, 20]
squares = for n <- numbers, do: n * n
IO.inspect(squares)A filter keeps only the long words
The test after the generator runs for each word. Only words that pass it reach the result.
words = ["apple", "fig", "banana", "kiwi"]
long_words = for word <- words, String.length(word) > 4, do: word
IO.inspect(long_words)Into builds a map of word lengths
With into: %{}, each item must give a pair of a key and a value. The pairs are collected into one map.
words = ["ant", "cat", "horse"]
lengths = for word <- words, into: %{}, do: {word, String.length(word)}
IO.inspect(lengths)Example
words = ["apple", "fig", "banana", "kiwi"]
shouted = for word <- words, do: String.upcase(word)
long_lengths =
for word <- words, String.length(word) > 3, into: %{} do
{word, String.length(word)}
end
IO.inspect(shouted)
IO.inspect(long_lengths)Key points
- Generator: the part written as name <- list, which pulls one item at a time from the source list.
- Do expression: the value after do, which is computed for each item and collected into the result.
- Source kept: a comprehension returns a new list and leaves the source list unchanged.
- Filter: an extra test after the generator, which keeps only the items that pass it.
- Into map: into: %{} collects pairs into a map instead of a list.
- Pair result: with into: %{}, the do expression must return a two-item tuple for each item.
In this example, the first comprehension upcases every word into a new list. The second keeps only words longer than three letters and collects each word with its length into a map.
Note
a comprehension over a list returns its items in the same order as the source.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does for x <- [200, 300], do: x + 10 return?