En

Enum in Elixir

92 exercises

About Enum

Enum is a very useful module that provides a set of algorithms for working with enumerables. It offers:

And much more! Refer to the Enum module documentation for a full list.

Enumerable

In general, an enumerable is any data that can be iterated over, a collection. In Elixir, an enumerable is any data type that implements the Enumerable protocol. Those are:

Don't worry if you don't know them all yet.

Anyone can implement the Enumerable protocol for their own custom data structure.

Reduce

Enum.reduce/2 allows you to reduce the whole enumerable to a single value. To achieve this, a special variable called the accumulator is used. The accumulator carries the intermediate state of the reduction between iterations. This makes it one of the most powerful functions for enumerables. Many other specialized functions could be replaced by the more general reduce. For example...

Finding the maximum value:

Enum.max([4, 20, 31, 9, 2])
# => 31

Enum.reduce([4, 20, 31, 9, 2], nil, fn x, acc ->
  cond do
    acc == nil -> x
    x > acc -> x
    x <= acc -> acc
  end
end)

# => 31

And even mapping (but it requires reversing the result afterwards):

Enum.map([1, 2, 3, 4, 5], fn x -> x + 10 end)
# => [11, 12, 13, 14, 15]

Enum.reduce([1, 2, 3, 4, 5], [], fn x, acc -> [x + 10 | acc] end)
# => [15, 14, 13, 12, 11]

Mapping maps

  • With Map.new/2:

    %{a: 1, b: 2}
    |> Map.new(fn {key, value} -> {key, value * 10} end)
    
  • With Enum.into/3:

    %{a: 1, b: 2}
    |> Enum.into(%{}, fn {key, value} -> {key, value * 10} end)
    
  • With Enum.map/2:

    %{a: 1, b: 2}
    |> Enum.map(fn {key, value} -> {key, value * 10} end)
    |> Enum.into(%{})
    
Edit via GitHub The link opens in a new window or tab

Learn Enum

Practicing is locked

Unlock 10 more exercises to practice Enum