Comprehensions at work
A comprehension in Elixir is a small language of its own: the generators say where the items come from, the filters say which ones go on, the options change the shape of the result, and the do part says what each item becomes. This page puts the parts together on data a program really meets: a map, two lists that cross, and a list with duplicates.
A generator over a map
A map yields its key-value pairs, so the pattern of the generator names both. The expression can read them, and a filter applies to the pair before the expression runs:
mapgen.exs
counts = %{apples: 3, pears: 5} IO.inspect(for {fruit, n} <- counts, do: "#{fruit}: #{n}") IO.inspect(for {fruit, n} <- counts, n > 3, do: fruit)
elixir mapgen.exs
["apples: 3", "pears: 5"]
[:pears]
The strings are the shape a report takes, and the atoms of the second line are the keys whose count passed the filter. The expression may use anything the pattern bound, and a name it does not bind comes from the code around the comprehension.
Two generators, and a filter that uses both
Two generators make every combination, and a filter after the second one may test both names. The result is the same list of tuples a nested loop would build, in the order the generators are written:
two.exs
suits = [:hearts, :spades] ranks = [1, 2, 3] IO.inspect(for suit <- suits, rank <- ranks, do: {suit, rank}) IO.inspect(for suit <- suits, rank <- ranks, suit == :spades, do: {suit, rank})
elixir two.exs
[hearts: 1, hearts: 2, hearts: 3, spades: 1, spades: 2, spades: 3]
[spades: 1, spades: 2, spades: 3]
The inspector writes a list of atom-value pairs in the keyword form, which is shorter than the tuples it stands for. The filter in the second line could equally compare the rank, and a program that needs only the pairs that pass both tests writes them one after the other, separated by commas.
uniq, and sorting the result
The comprehension has options of its own. uniq: true keeps the first occurrence of each result, which is the deduplication inside the loop rather than a pass after it. The result is a list like any other, so the functions of Enum finish the work:
uniq.exs
words = ["pear", "fig", "apple", "fig"] IO.inspect(for w <- words, uniq: true, do: String.upcase(w)) lengths = for w <- words, do: String.length(w) IO.inspect(Enum.sort(lengths)) IO.inspect(Enum.frequencies(lengths))
elixir uniq.exs
["PEAR", "FIG", "APPLE"]
[3, 3, 4, 5]
%{3 => 2, 4 => 1, 5 => 1}
The two lists of lengths differ because the uniq: was not repeated in the second one: fig appears twice, so 3 appears twice. A comprehension gives one list, and Enum.sort/1 or Enum.frequencies/1 answers the shape the report needs.
The mistake: the name after the comprehension
A generator binds its names inside the comprehension only. Using one after the for has ended is a compile error, and the message points at the name that no longer exists:
mistake.exs
doubles = for item <- [1, 2, 3], do: item * 2 IO.inspect(doubles) IO.inspect(item)
elixir mistake.exs
error: undefined variable "item"
│
4 │ IO.inspect(item)
│ ^^^^
│
└─ mistake.exs:4:12
** (CompileError) mistake.exs: cannot compile file (errors have been logged)
The value the comprehension produced is doubles, and that is what the next line uses. A program that needs the last value of the loop binds it inside, with List.last/1 or a reduce, and a program that needs every name binds the whole list. The variable of a generator is as local as the parameter of a function.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a generator over a map yield?
Answer
a key-value pair per entry
A map enumerates as its pairs, so the pattern of the generator takes both parts.
-
What does
uniq: truedo in a comprehension?Answer
It keeps the first occurrence of each result
The option drops a repeated result as the list is built, so the first one stays.
-
Where does a name bound by a generator exist?
Answer
Only inside the comprehension
The generator variable is local to the for, like the parameter of a function.
-
What does a filter between two generators see?
Answer
both names bound so far
A filter applies at the place it is written, and every name bound before it is in scope.
-
What does this program print?
IO.inspect(for {k, v} <- [a: 1, b: 2], do: {k, v * 2})Answer
[a: 2, b: 4]
The comprehension builds a list of pairs, printed in the keyword form.
-
What does this program print?
IO.inspect(for x <- ["a", "b"], y <- ["!"], do: x <> y)Answer
["a!", "b!"]
The outer generator runs twice and each value is joined to the single value of the inner one.
-
What does this program print?
IO.inspect(for w <- ["a", "a", "b"], uniq: true, do: w)Answer
["a", "b"]
The repeated result is dropped as it is built, so the first a stays and the second does not.
-
What does this program print?
lengths = for w <- ["a", "bb"], do: String.length(w) IO.inspect(Enum.sort(lengths))Answer
[1, 2]
The comprehension gives the lengths, and sort puts the smaller number first.
-
What does this program do?
squares = for n <- [1, 2], do: n * n IO.inspect(squares) IO.inspect(n)Answer
error: undefined variable "n", because the name lives only inside the for
The generator variable is local, so the line after the for cannot see it and the file does not compile.
-
What does this program print?
IO.inspect(for n <- 1..3, n != 2, do: n * 10)Answer
[10, 30]
The filter drops 2, and the expression multiplies the two remaining values by ten.
Article author: Arthur Isaev