O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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​​
     

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required