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

The Collectable Protocol

The Enumerable protocol lets you iterate over the elements in a type—given a collection, you can get the elements. Collectable is in some sense the opposite—it allows you to build a collection by inserting elements into it.

Not all collections are collectable. Ranges, for example, cannot have new entries added to them.

The collectable API is pretty low-level, so you’ll typically access it via Enum.into and when using comprehensions (which we cover in the next section). For example, we can inject the elements of a range into an empty list using

 
iex>​ Enum.into 1..5, []
 
[1, 2, 3, 4, 5]

If the list is not empty, the new elements are tacked onto the end:

 
iex>​ Enum.into 1..5, [100, 101 ]
 
[100, 101, 1, 2, 3, 4, 5] ...

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