Comprehensions in Elixir

A comprehension is the loop of Elixir, written as a for with one or more generators. It builds a list from the items a generator produces, keeps the items its filters accept, and with into: pours the result into a collection of another type. It is a call, not a statement: the value of the for is what it built.

A for and its generator

The generator is item <- source, read as "each item of the source". One generator and one expression produce a list as long as the source, and the expression is the do part:

basic.exs

IO.inspect(for n <- [1, 2, 3], do: n * 2) IO.inspect(for n <- [1, 2, 3, 4], rem(n, 2) == 0, do: n)

elixir basic.exs

[2, 4, 6]
[2, 4]

The second for has a filter between the generator and the do: the expression rem(n, 2) == 0 decides whether the item is kept, and it accepts a truthy value rather than a boolean in the strict sense. The long form of the same call uses a block with do and end, which the formatter prefers once the expression is more than a line.

Filters and a second generator

A second generator nests the loops: every value of the first is paired with every value of the second. A filter may use both names, and the order of the output follows the order of the generators:

pairs.exs

IO.inspect(for a <- [1, 2], b <- [:x, :y], do: {a, b}) IO.inspect(for x <- 1..3, y <- 1..x, do: {x, y})

elixir pairs.exs

[{1, :x}, {1, :y}, {2, :x}, {2, :y}]
[{1, 1}, {2, 1}, {2, 2}, {3, 1}, {3, 2}, {3, 3}]

The second line is the triangle: the range of the inner generator depends on the value of the outer one, which no single Enum call expresses so shortly. A filter applies at the point it is written, so a filter after the second generator can use x and y both.

The into: option

Without into: the result is a list. The option names a collectable, the same targets Enum.into/2 takes, and the pairs of the expression become the entries of the map:

into.exs

pairs = for n <- [1, 2, 3], do: {n, n * n} IO.inspect(pairs) IO.inspect(for n <- [1, 2, 3], into: %{}, do: {n, n * n}) IO.inspect(for w <- ["a", "b", "a"], into: MapSet.new(), do: w)

elixir into.exs

[{1, 1}, {2, 4}, {3, 9}]
%{1 => 1, 2 => 4, 3 => 9}
MapSet.new(["a", "b"])

The keyword list is the fourth target, into: [] with pairs of an atom and a value, and it keeps the order of the generators. The conversions lesson covers the four collections and what each one does with a duplicate.

A pattern in the generator

The left side of a generator is a pattern, so a list of maps is walked by naming the fields the expression needs. An item that does not fit the pattern is skipped rather than failing the loop, which makes a mixed list safe to read:

pattern.exs

people = [%{name: "Ada", age: 36}, %{name: "Bob", age: 12}, %{name: "Cy", age: 41}] IO.inspect(for %{name: name, age: age} <- people, age >= 18, do: name) IO.inspect(for {key, value} <- %{a: 1}, do: {key, value + 1})

elixir pattern.exs

["Ada", "Cy"]
[a: 2]

The second line walks a map as its key-value pairs and builds a list of pairs, which the inspector shows in the keyword form because both items are an atom and a value. A generator over a map therefore sees {key, value}, never the values alone; Map.values/1 is the call for those.

A for or an Enum call

A comprehension and a chain of Enum calls can express the same work. The comprehension reads better when the program filters and maps in one thought, when a generator depends on an earlier one, or when the result is a map or a set. The Enum chain reads better for a single step, and for a step the module already names, such as Enum.sum/1 or Enum.group_by/3. Neither is lazy: both build their result at once, and Stream is the module that waits.

The mistake: a source that is not enumerable

A generator walks a source through the Enumerable protocol, and a number has no implementation of it. The program stops with a Protocol.UndefinedError that names the type it was given:

mistake.exs

IO.inspect(for n <- 5, do: n * 2)

elixir mistake.exs

** (Protocol.UndefinedError) protocol Enumerable not implemented for Integer

Got value:

    5

    (elixir 1.19.7) lib/enum.ex:5: Enumerable.impl_for!/1
    (elixir 1.19.7) lib/enum.ex:170: Enumerable.reduce/3
    (elixir 1.19.7) lib/enum.ex:4570: Enum.map/2
    mistake.exs:1: (file)

The source has to be a collection: 1..5 for the numbers, a list for a fixed set of values, a map or a MapSet for a lookup structure. A single value that the program wants to repeat goes into a list first, for n <- [5], do: n * 2, and a comprehension over an empty list answers an empty list rather than failing.

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.

  1. What does a for comprehension return when it has no into: option?

    Answer

    A list

    The default target is a list, and the value of the for is what it built.

  2. What happens to an item that does not fit the pattern on the left of a generator?

    Answer

    It is skipped

    A generator is a filter as well as a loop, so a non-matching item is simply not used.

  3. What does a second generator do?

    Answer

    It nests the loops, pairing every value of the first with every value of the second

    Each generator adds a loop level, and the order of the output follows their order.

  4. Which option pours the result into a map or a set?

    Answer

    into:

    into: names the collectable, and the expression must return the pairs a map needs.

  5. What does this program print? IO.inspect(for n <- [1, 2, 3], do: n * 2)

    Answer

    [2, 4, 6]

    The expression is applied to every item and the results form the list.

  6. What does this program print? IO.inspect(for n <- 1..6, rem(n, 2) == 0, do: n)

    Answer

    [2, 4, 6]

    The filter keeps the even numbers of the range.

  7. What does this program print? IO.inspect(for n <- [1, 2], into: %{}, do: {n, n * n})

    Answer

    %{1 => 1, 2 => 4}

    The pairs become the entries of the map the into: option names.

  8. What does this program print? IO.inspect(for a <- [1, 2], b <- [:x], do: {a, b})

    Answer

    [{1, :x}, {2, :x}]

    The outer generator runs twice and the inner one once, so there are two pairs.

  9. What does this program do? IO.inspect(for n <- 5, do: n * 2)

    Answer

    A Protocol.UndefinedError, because a number is not enumerable

    A generator walks an enumerable, and an integer has no Enumerable implementation.

  10. What does a generator over a map produce?

    Answer

    the key-value pairs

    A map enumerates as its pairs, so the pattern in the generator sees {key, value}.

Автор статьи: Arthur Isaev