group_by, sort_by and the aggregates

The functions of Enum in Elixir answer one value per call, and the ones on this page answer a summary of many: a map of groups, a sorted list, a count per value, a smallest and a largest. They are the functions a report is made of, and they compose with each other in a pipeline that reads top to bottom.

group_by

Enum.group_by/2 takes a key function and answers a map whose keys are the results and whose values are the items that produced each key. A third argument transforms the items as they are put into their group, which saves a second pass:

group.exs

words = ["apple", "fig", "pear", "plum", "kiwi"] IO.inspect(Enum.group_by(words, &String.length/1)) IO.inspect(Enum.group_by(words, &String.first/1)) IO.inspect(Enum.group_by(words, &String.length/1, &String.upcase/1))

elixir group.exs

%{3 => ["fig"], 4 => ["pear", "plum", "kiwi"], 5 => ["apple"]}
%{"a" => ["apple"], "f" => ["fig"], "k" => ["kiwi"], "p" => ["pear", "plum"]}
%{3 => ["FIG"], 4 => ["PEAR", "PLUM", "KIWI"], 5 => ["APPLE"]}

The items of a group keep the order they had in the input, so the map is the only reordering in the result. A group key may be any value the program can compare, and the keys of the map are whatever the function returned: an integer from String.length/1, a binary from String.first/1.

sort_by, and the descending order

Enum.sort_by/2 sorts by a key rather than by the item, so a list of tuples is sorted by one of its positions without building a new list. The third argument is the sorter, :asc by default or :desc, and a sort is stable: two items with the same key keep their relative order:

sort.exs

scores = [{"Ada", 90}, {"Bob", 75}, {"Cy", 90}] IO.inspect(Enum.sort_by(scores, fn {_name, score} -> score end)) IO.inspect(Enum.sort_by(scores, fn {_name, score} -> score end, :desc)) IO.inspect(Enum.sort_by(scores, &elem(&1, 1), :desc))

elixir sort.exs

[{"Bob", 75}, {"Ada", 90}, {"Cy", 90}]
[{"Ada", 90}, {"Cy", 90}, {"Bob", 75}]
[{"Ada", 90}, {"Cy", 90}, {"Bob", 75}]

The pattern in the function head takes the tuple apart and the capture reads position 1, which is the same key in two spellings. The stable order is why Ada stays before Cy in the descending sort: both have 90 and the input had them in that order. A second sort by name would be needed to make the tie break predictable.

frequencies and the aggregates

Enum.frequencies/1 counts how often each value appears, and Enum.frequencies_by/2 counts by a key. The aggregates min, max, sum and min_max answer over a list, and each has a _by form that compares a key:

aggregates.exs

IO.inspect(Enum.frequencies(["a", "b", "a"])) IO.inspect(Enum.frequencies_by(["apple", "fig", "pear"], &String.length/1)) IO.puts(Enum.min([3, 1, 2])) IO.puts(Enum.max([3, 1, 2])) IO.puts(Enum.sum([3, 1, 2])) IO.inspect(Enum.min_max([3, 1, 2]))

elixir aggregates.exs

%{"a" => 2, "b" => 1}
%{3 => 1, 4 => 1, 5 => 1}
1
3
6
{1, 3}

Enum.min_max/1 walks the list once and answers both ends as a tuple, where two separate calls walk it twice. Enum.min_by/2 and Enum.max_by/2 answer the item itself rather than its key, which is how a program finds the longest word rather than its length.

A group, then a sum

Computing a total per group takes two steps: group the rows and keep the amount of each, then reduce each group to one number. The pipeline below writes both steps with the functions of this page and Map.new/2, and the result is one map from a name to its total:

pipeline.exs

sales = [{"apple", 3}, {"pear", 5}, {"apple", 2}] by_fruit = Enum.group_by(sales, &elem(&1, 0), &elem(&1, 1)) IO.inspect(by_fruit) totals = Map.new(by_fruit, fn {fruit, amounts} -> {fruit, Enum.sum(amounts)} end) IO.inspect(totals)

elixir pipeline.exs

%{"apple" => [3, 2], "pear" => [5]}
%{"apple" => 5, "pear" => 5}

The first call already keeps only the amounts, because the third argument of Enum.group_by/3 transformed each row. Without it the groups would hold the whole tuples and the sum would need another map. This shape, group and then aggregate, is the one to reach for before a loop over a map is written by hand.

The mistake: an aggregate of an empty list

Enum.min/1 has no answer for an empty list and says so with an Enum.EmptyError. A group that a filter removed is exactly how a program reaches that call with nothing to give:

mistake.exs

IO.inspect(Enum.min([]))

elixir mistake.exs

** (Enum.EmptyError) empty error
    (elixir 1.19.7) lib/enum.ex:2069: anonymous fn/0 in Enum.min/1
    mistake.exs:1: (file)

The bang-free answer is Enum.min/2 with a default, Enum.min(list, fn -> nil end), or a check of the list before the call. A program that aggregates a group should decide what an empty group means: zero for a sum, which Enum.sum/1 gives, and nothing for a minimum, which has to be written.

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.group_by/2 answer?

    Answer

    A map from each key to the items that produced it

    The key function decides the keys of a map, and each value is the list of its items.

  2. What does the third argument of Enum.group_by/3 do?

    Answer

    It transforms each item before it goes into its group

    The value function maps each item to what the group holds, such as an amount rather than a row.

  3. What does Enum.frequencies/1 answer?

    Answer

    A map from each value to how often it appears

    The result is a map of value to count, which is what a report needs.

  4. Why is a second sort needed when two items have the same key?

    Answer

    Together with the first sort for a predictable tie break

    The sort is stable, so the tie keeps the input order; a second key makes the order deliberate.

  5. What does this program print? IO.inspect(Enum.frequencies(["a", "b", "a"]))

    Answer

    %{"a" => 2, "b" => 1}

    The value a appears twice and b once, and the map counts each one.

  6. What does this program print? IO.inspect(Enum.min_max([3, 1, 2]))

    Answer

    {1, 3}

    min_max/1 answers the smallest first and the largest second, as a tuple.

  7. What does this program print? IO.puts(Enum.sum([]))

    Answer

    0

    The sum of nothing is zero, which is why sum needs no empty-list answer.

  8. What does this program do? IO.inspect(Enum.min([]))

    Answer

    An Enum.EmptyError, because the list has no minimum

    A minimum of an empty list does not exist, and Enum says so with an empty error.

  9. What does this program print? IO.inspect(Enum.sort_by([3, 1, 2], &(-&1)))

    Answer

    [3, 2, 1]

    The key is the negated value, so the largest number has the smallest key and comes first.

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

    Answer

    %{3 => 1, 4 => 1, 5 => 1}

    frequencies_by counts the items per key, so each length appears once.

Article author: Arthur Isaev