Elixir Enumerables & Streams
The Enum module is the workhorse of everyday Elixir. It works with any enumerable: lists, maps, ranges, MapSets, streams and your own data types that implement the Enumerable protocol. Every Enum function is eager: it walks the whole collection and returns a result right away.
Ranges
A range first..last (or first..last//step) is an enumerable of integers that doesn't store its elements:
IO.inspect(Enum.to_list(1..5))
IO.inspect(Enum.to_list(10..0//-3))
IO.inspect(Enum.sum(1..100))
IO.inspect(Enum.count(1..1_000_000))[1, 2, 3, 4, 5]
[10, 7, 4, 1]
5050
1000000
The most used Enum functions
orders = [
%{id: 1, customer: "Ana", total: 30.0, status: :paid},
%{id: 2, customer: "Ben", total: 12.5, status: :pending},
%{id: 3, customer: "Ana", total: 99.9, status: :paid},
%{id: 4, customer: "Cleo", total: 45.0, status: :refunded}
]
paid = Enum.filter(orders, &(&1.status == :paid))
IO.inspect(Enum.map(paid, & &1.id))
IO.inspect(Enum.reject(orders, &(&1.status == :paid)) |> Enum.map(& &1.id))
IO.inspect(Enum.reduce(orders, 0, fn o, acc -> acc + o.total end))
IO.inspect(Enum.find(orders, &(&1.total > 40)).id)
IO.inspect(Enum.any?(orders, &(&1.status == :refunded)))
IO.inspect(Enum.all?(orders, &(&1.total > 10)))
IO.inspect(Enum.max_by(orders, & &1.total).customer)
IO.inspect(Enum.sort_by(orders, & &1.total, :desc) |> Enum.map(& &1.id))[1, 3]
[2, 4]
187.4
3
true
true
"Ana"
[3, 4, 1, 2]
| Function | Returns |
|---|---|
map(e, f) |
a list with f applied to each element |
filter(e, f) / reject(e, f) |
the elements for which f is truthy / falsy |
reduce(e, acc, f) |
one value built by folding every element into the accumulator |
find(e, f) |
the first matching element, or nil |
any? / all? / count |
booleans / a count |
sort, sort_by, max_by, min_by |
ordering helpers |
take(e, n), drop(e, n), chunk_every(e, n) |
slices and chunks |
group_by, frequencies, uniq, zip, with_index |
reshaping |
Grouping and counting
words = ~w(apple avocado banana blueberry cherry apple banana apple)
IO.inspect(Enum.frequencies(words))
IO.inspect(Enum.group_by(words, &String.first/1) |> Map.get("b"))
IO.inspect(Enum.uniq(words))
IO.inspect(Enum.chunk_every(1..7, 3))
IO.inspect(Enum.with_index(["gold", "silver", "bronze"], 1))
IO.inspect(Enum.join(["a", "b", "c"], ", "))
IO.inspect(Enum.map_join(1..3, "-", &(&1 * 10)))%{"apple" => 3, "avocado" => 1, "banana" => 2, "blueberry" => 1, "cherry" => 1}
["banana", "blueberry", "banana"]
["apple", "avocado", "banana", "blueberry", "cherry"]
[[1, 2, 3], [4, 5, 6], ~c"\a"]
[{"gold", 1}, {"silver", 2}, {"bronze", 3}]
"a, b, c"
"10-20-30"
~w(...) is a sigil that splits words into a list of strings (see the Sigils lesson). Look at the chunks: the last one, [7], is printed as ~c"\a". That is the charlist surprise from the Strings lesson: 7 is the code point of the "bell" control character, and inspect shows any list made only of such printable or escapable code points as a charlist. The value is still the list [7].
Enum on maps
Functions in Enum see a map as a list of {key, value} tuples, and they always return a list. Use Map.new/2 or Enum.into/2 to get a map back:
inventory = %{"pens" => 3, "paper" => 0, "ink" => 7}
low = Enum.filter(inventory, fn {_item, qty} -> qty < 5 end)
IO.inspect(Enum.sort(low))
doubled = Map.new(inventory, fn {item, qty} -> {item, qty * 2} end)
IO.inspect(doubled)
IO.inspect(Enum.into([a: 1, b: 2], %{}))[{"paper", 0}, {"pens", 3}]
%{"ink" => 14, "paper" => 0, "pens" => 6}
%{a: 1, b: 2}
Streams: lazy enumeration
A stream describes a computation without running it. Functions in Stream return a new stream; nothing happens until an Enum function (or Stream.run/1) asks for the values. This avoids building big intermediate lists and makes infinite sequences possible:
squares_of_odds =
1..1_000_000
|> Stream.filter(&(rem(&1, 2) == 1))
|> Stream.map(&(&1 * &1))
IO.inspect(Enum.take(squares_of_odds, 5))
# Infinite streams
IO.inspect(Stream.iterate(1, &(&1 * 2)) |> Enum.take(10))
IO.inspect(Stream.cycle([:red, :green]) |> Enum.take(5))
fib = Stream.unfold({0, 1}, fn {a, b} -> {a, {b, a + b}} end)
IO.inspect(Enum.take(fib, 12))[1, 9, 25, 49, 81]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
[:red, :green, :red, :green, :red]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
With Enum.filter the first line would build a 500,000-element list first. With Stream only the first five odd numbers are ever squared.
Seeing the laziness
The order of the printed lines shows that a stream processes one element through the whole pipeline before the next element starts, while Enum finishes each step for all elements first:
IO.puts("Enum:")
[1, 2, 3]
|> Enum.map(fn x -> IO.puts(" map #{x}"); x * 10 end)
|> Enum.each(fn x -> IO.puts(" each #{x}") end)
IO.puts("Stream:")
[1, 2, 3]
|> Stream.map(fn x -> IO.puts(" map #{x}"); x * 10 end)
|> Enum.each(fn x -> IO.puts(" each #{x}") end)Enum:
map 1
map 2
map 3
each 10
each 20
each 30
Stream:
map 1
each 10
map 2
each 20
map 3
each 30
Tip: Use
Enumby default. Reach forStreamwhen the data is large, infinite, or comes from a resource such as a file (File.stream!/1) that you want to read line by line.
Test yourself
What does Enum.map(%{a: 1}, fn {k, v} -> {k, v + 1} end) return?
%{a: 2}[a: 2]{:a, 2}- An error
When does Stream.map(1..3, &(&1 * 2)) compute its values?
- Immediately
- Only when an Enum function (or Stream.run) consumes the stream
- In a background process
- Never
What is Enum.reduce([1, 2, 3], 10, fn x, acc -> acc + x end)?
- 6
- 16
- 10
- [11, 12, 13]