Enum in Elixir

Enum is the module a collection lives on. It walks any value that can be enumerated, which in Elixir means lists, tuples, maps, ranges, MapSets and the streams of the next part of the course, and it answers a plain list or a single value. The three functions below cover most programs; everything else in the module is a variation on them.

map and filter

Enum.map/2 applies a function to every item and returns the list of results. Enum.filter/2 keeps the items whose function answers a truthy value, and Enum.reject/2 keeps the others. All three return a new list and leave the input untouched:

map.exs

numbers = [1, 2, 3, 4, 5] IO.inspect(Enum.map(numbers, fn n -> n * 2 end)) IO.inspect(Enum.filter(numbers, fn n -> rem(n, 2) == 0 end)) IO.inspect(Enum.reject(numbers, fn n -> rem(n, 2) == 0 end))

elixir map.exs

[2, 4, 6, 8, 10]
[2, 4]
[1, 3, 5]

The function goes in as a value, and the shortest way to write a value that is a function is the capture, &(&1 * 2), which names its first argument as &1. The next section takes the forms apart.

reduce folds a list into one value

Enum.reduce/3 carries an accumulator through the list. The function receives the item and the accumulator so far, and the value it returns is the accumulator for the next step; the value of the last step is the answer. A sum, a concatenation and a count are all the same shape:

reduce.exs

IO.puts(Enum.reduce([1, 2, 3], 0, fn n, acc -> n + acc end)) IO.puts(Enum.sum([1, 2, 3])) IO.inspect(Enum.reduce(["a", "b"], "", fn word, acc -> acc <> word end))

elixir reduce.exs

6
6
"ab"

Enum.sum/1 is the addition written once for every reader, and a reduce of a list of strings shows the general form. When the accumulator is a list that is built item by item, the list lesson applies: prepend and reverse once at the end rather than appending in every step.

The capture shorthand

&f/1 is a named function as a value, and &(...) is a short anonymous function whose arguments are &1, &2 and so on. The two forms make a call to a module function read like a sentence, and the compiler checks that the arity is right:

capture.exs

words = ["pear", "fig", "apple"] IO.inspect(Enum.map(words, &String.upcase/1)) IO.inspect(Enum.map(words, &String.length/1)) IO.inspect(Enum.map([1, 2, 3], &(&1 * 10)))

elixir capture.exs

["PEAR", "FIG", "APPLE"]
[4, 3, 5]
[10, 20, 30]

&String.length/1 passes the function itself, while &String.length/2 is a different value and a compile error where one argument is expected. A capture that ignores its argument is a warning, which functions covers with the rest of the shorthand.

find, any?, all? and sort

The rest of the module answers questions about a list. Enum.find/2 returns the first item that matches, any?/2 and all?/2 answer a boolean, Enum.sort_by/2 sorts by a key, and Enum.uniq/1 removes duplicates:

search.exs

words = ["pear", "fig", "apple"] IO.inspect(Enum.sort(words)) IO.inspect(Enum.sort_by(words, &String.length/1)) IO.inspect(Enum.find(words, &(String.length(&1) == 3))) IO.puts(Enum.any?(words, &String.starts_with?(&1, "f"))) IO.puts(Enum.all?(words, &is_binary/1)) IO.inspect(Enum.uniq([1, 2, 1, 3, 2]))

elixir search.exs

["apple", "fig", "pear"]
["fig", "pear", "apple"]
"fig"
true
true
[1, 2, 3]

Enum.find/2 answers nil when nothing matches, so a program that expects an item checks the answer. The sort of strings is by code point, which puts "apple" before "fig"; the sort by length keeps the original order of two items of the same length, which is what makes it stable.

Eager, and over more than lists

Every function of Enum does its work at once and returns a list, however long the input was. A map is enumerated as its key-value pairs, a range as its numbers, and a MapSet as its members, so the same call reads the same way for all of them:

The eagerness is the difference from Stream: a chain of five Enum calls walks the list five times and builds five lists, which is fine for the sizes a program usually handles and wrong for a file of a million rows.

The mistake: the result that is dropped

A reader who comes from a language with mutable collections calls Enum.map/2 for its side effect and expects the list to change. The function returns a new list, and the old one is what the next line prints:

mistake.exs

numbers = [1, 2, 3] Enum.map(numbers, fn n -> n * 2 end) IO.inspect(numbers)

elixir mistake.exs

[1, 2, 3]

Nothing failed, and the program is still wrong. The fix is to bind the result, doubled = Enum.map(numbers, fn n -> n * 2 end), and use it. The compiler does not warn about an unused call result, because the call may have printed or sent a message; the reader is the one who keeps the value. Every function of an immutable collection shares the trap, from Enum to Map.put/3.

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 Enum.map/2 return?

    Answer

    A new list with one result per item

    Enum is eager: it walks the input and builds a new list, leaving the input as it was.

  2. What does Enum.reduce/3 carry through the list?

    Answer

    An accumulator, from one step to the next

    The function receives the item and the accumulator, and returns the accumulator for the next step.

  3. What does the capture &String.length/1 mean?

    Answer

    A function value that calls String.length with one argument

    The shorthand names a function and its arity, so it can be passed as a value.

  4. Why is a chain of Enum calls eager rather than lazy?

    Answer

    Because each call walks the input and builds a list at once

    Enum does the work in the call; Stream is the module that waits for the final Enum.

  5. What does this program print? IO.inspect(Enum.map([1, 2, 3], fn n -> n * 2 end))

    Answer

    [2, 4, 6]

    The function doubles each item and the result is the list of doubles.

  6. What does this program print? IO.inspect(Enum.filter([1, 2, 3, 4], fn n -> rem(n, 2) == 0 end))

    Answer

    [2, 4]

    The filter keeps the items whose rem is zero, in the order they come.

  7. What does this program print? IO.puts(Enum.reduce([1, 2, 3, 4], 0, fn n, acc -> n + acc end))

    Answer

    10

    The accumulator starts at 0 and each item is added to it.

  8. What does this program print? IO.inspect(Enum.sort_by(["pear", "fig", "apple"], &String.length/1))

    Answer

    ["fig", "pear", "apple"]

    The sort uses the length as the key, and the shortest word comes first.

  9. What does this program print? numbers = [1, 2, 3] Enum.map(numbers, fn n -> n * 2 end) IO.inspect(numbers)

    Answer

    [1, 2, 3]

    map returns a new list and the binding still holds the old one, which is printed.

  10. What does this program print? IO.inspect(Enum.find([1, 2, 3], &(&1 > 1)))

    Answer

    2

    find returns the first item that matches the function.

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