Enum—Processing Collections

The Enum module is probably the most used of all the Elixir libraries. 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, ...

Get Programming Elixir 1.2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.