Enum: Processing Collections

Learn functionalities which can be performed with the help of the Enum module.

We'll cover the following

Introduction

The Enum module is probably the most used of all the Elixir libraries. We can employ it to iterate, filter, combine, split, and otherwise manipulate collections. Here are some common tasks:

  • Convert any collection into a list:
   iex> list = Enum.to_list 1..5
   [1, 2, 3, 4, 5]
  • Concatenate collections:
   iex> Enum.concat([1,2,3], [4,5,6]) 
   [1, 2, 3, 4, 5, 6]
   iex> Enum.concat [1,2,3], 'abc' 
   [1, 2, 3, 97, 98, 99]
  • Create collections whose elements are some function of the original:
   iex> Enum.map(list, &(&1 * 10))
   [10, 20, 30, 40, 50]
   iex> Enum.map(list, &String.duplicate("*", &1)) 
   ["*", "**", "***", "****", "*****"]
  • Select elements by position or criteria:
   iex> Enum.at(10..20, 3)
   13
   iex> Enum.at(10..20, 20)
   nil
   iex> Enum.at(10..20, 20, :no_one_here) 
   :no_one_here
   iex> require Integer # to get access to is_even 
   Integer
   iex> Enum.filter(list, &Integer.is_even/1)
   [2, 4]
   iex> Enum.reject(list, &Integer.is_even/1)
   [1, 3, 5]
  • Sort and compare elements:
   iex> Enum.sort ["there", "was", "a", "crooked", "man"] 
   ["a", "crooked", "man", "there", "was"]
   iex> Enum.max ["there", "was", "a", "crooked", "man"]
   "was"
   iex> Enum.max_by ["there", "was", "a", "crooked", "man"], &String.length/1 
   "crooked"
  • Split a collection:
   iex> Enum.take(list, 3)
   [1, 2, 3]
   iex> Enum.split(list, 3)
   {[1, 2, 3], [4, 5]}
   iex> Enum.split_while(list, &(&1 < 4))
   {[1, 2, 3], [4, 5]}
  • Join a collection:
   iex> Enum.join(list)
   "12345"
   iex> Enum.join(list, ", ") 
   "1, 2, 3, 4, 5"
  • Predicate operations:
   iex> Enum.all?(list, &(&1 < 4))
   false
   iex> Enum.any?(list, &(&1 < 4))
   true
   iex> Enum.member?(list, 4)
   true
   iex> Enum.empty?(list)
   false
  • Merge collections:
   iex> Enum.zip(list, [:a, :b, :c])
   [{1, :a}, {2, :b}, {3, :c}]
   iex> Enum.with_index(["once", "upon", "a", "time"]) 
   [{"once", 0}, {"upon", 1}, {"a", 2}, {"time", 3}]
  • Fold elements into a single value:
   iex> Enum.reduce(1..100, &(&1+&2))
   5050
   iex> Enum.reduce(["now", "is", "the", "time"],fn word, longest ->
   ...>       if String.length(word)> String.length(longest) do
   ...>          word
   ...>       else
   ...>          longest
   ...>       end
   ...> end)
   "time"

Get hands-on with 1200+ tech skills courses.