TExcelTAD
Home › Elixir › Elixir Comprehensions

Elixir Comprehensions

A comprehension (for) loops over one or more enumerables, optionally filters the elements, and collects the results. It combines Enum.map, Enum.filter and nested loops in one readable expression. It is not a loop with side effects like for in C or Java: it is an expression that returns a list (or another collectable).

elixir · try it yourself
squares = for n <- 1..5, do: n * n
IO.inspect(squares)

evens = for n <- 1..10, rem(n, 2) == 0, do: n
IO.inspect(evens)
[1, 4, 9, 16, 25]
[2, 4, 6, 8, 10]

The parts of a comprehension:

Part Example Meaning
generator n <- 1..10 take each element
filter rem(n, 2) == 0 keep only elements where it is truthy
do: body n * n the value to collect
options into:, uniq:, reduce: change what is collected

Multiple generators

With two or more generators, the comprehension takes every combination, like nested loops (the last generator changes fastest):

elixir · try it yourself
sizes = ["S", "M"]
colors = [:red, :blue]

variants = for size <- sizes, color <- colors, do: "#{size}-#{color}"
IO.inspect(variants)

# Later generators can use earlier variables
pairs = for a <- 1..4, b <- a..4, a + b == 5, do: {a, b}
IO.inspect(pairs)
["S-red", "S-blue", "M-red", "M-blue"]
[{1, 4}, {2, 3}]

Pattern matching in generators

The left side of <- is a pattern. Elements that don't match it are skipped silently, which is a neat way to filter tagged data:

elixir · try it yourself
results = [{:ok, "report.pdf"}, {:error, :timeout}, {:ok, "photo.jpg"}, {:error, :refused}]

values = for {:ok, v} <- results, do: v
IO.inspect(values)

errors = for {:error, reason} <- results, do: reason
IO.inspect(errors)

people = [%{name: "Zoe", age: 17}, %{name: "Omar", age: 34}, %{name: "Kim", age: 21}]
adults = for %{name: name, age: age} <- people, age >= 18, do: name
IO.inspect(adults)
["report.pdf", "photo.jpg"]
[:timeout, :refused]
["Omar", "Kim"]

into: collect into a map or string

By default a comprehension returns a list. into: collects into any collectable, such as a map or a string:

elixir · try it yourself
prices = %{"tea" => 3.0, "cake" => 4.5, "juice" => 2.75}

discounted = for {item, price} <- prices, into: %{}, do: {item, price * 0.9}
IO.inspect(discounted)

acronym = for word <- String.split("portable network graphics"), into: "", do: String.first(word)
IO.inspect(String.upcase(acronym))
%{"cake" => 4.05, "juice" => 2.475, "tea" => 2.7}
"PNG"

uniq: and reduce:

uniq: true drops duplicate results. reduce: turns the comprehension into a fold: the body is a set of acc -> ... clauses and the result is the final accumulator:

elixir · try it yourself
first_letters = for w <- ~w(apple avocado banana cherry cranberry), uniq: true, do: String.first(w)
IO.inspect(first_letters)

text = "the cat and the hat and the bat"

counts =
  for word <- String.split(text), reduce: %{} do
    acc -> Map.update(acc, word, 1, &(&1 + 1))
  end

IO.inspect(counts["the"])
IO.inspect(counts["and"])
["a", "b", "c"]
3
2

Bitstring generators

<<c <- binary>> iterates over the bytes of a binary. This example converts a string of RGB bytes into tuples:

elixir · try it yourself
pixels = <<255, 0, 0, 0, 255, 0, 0, 0, 255>>
rgb = for <<r, g, b <- pixels>>, do: {r, g, b}
IO.inspect(rgb)

IO.inspect(for <<c <- "hello">>, c != ?l, into: "", do: <<c>>)
[{255, 0, 0}, {0, 255, 0}, {0, 0, 255}]
"heo"

Comprehension or Enum?

They are interchangeable for simple cases; choose whichever reads better:

elixir
for x <- list, x > 0, do: x * 2
# is the same as
list |> Enum.filter(&(&1 > 0)) |> Enum.map(&(&1 * 2))

Comprehensions win with multiple generators, pattern-based filtering and into:. Pipelines win for long chains of transformations.

Note: Variables assigned inside the body of a for are not visible after it. To build up a result, use the returned value or reduce:.

Test yourself

What does for x <- [1, 2, 3], x > 1, do: x * 10 return?

  1. [10, 20, 30]
  2. [20, 30]
  3. 60
  4. [2, 3]

What happens to elements that don't match the generator pattern in for {:ok, v} <- list?

  1. A MatchError is raised
  2. They are skipped
  3. They are returned as nil
  4. The comprehension stops

How do you make a comprehension return a map?

  1. for ..., as: :map
  2. for ..., into: %{} with a body that returns {key, value}
  3. Map.for
  4. Wrap it in %{...}