The Collectable Protocol
Understand how the collectable protocol works in Elixir.
We'll cover the following
Introduction
The Enumerable
protocol lets us iterate over the elements in a type. Given a collection, we can get the elements. The Collectable
protocol is in some sense the opposite. It allows us to build a collection by inserting elements into it.
Not all collections are collectable. Ranges, for example, can’t have new entries added to them.
Examples
The Collectable
API is pretty low-level, so we’ll typically access it via Enum.into
and when we’re using comprehensions (which we cover in the next lesson). For example, we can inject the elements of a range into an empty list using the following:
iex> Enum.into 1..5, []
[1, 2, 3, 4, 5]
If the list isn’t empty, the new elements are tacked onto the end:
iex> Enum.into 1..5, [ 100, 101 ]
[100, 101, 1, 2, 3, 4, 5]
Output streams are collectable, so the following code lazily copies standard input (we’ll have to enter some input) to standard output:
iex> Enum.into IO.stream(:stdio, :line), IO.stream(:stdio, :line)
Use the terminal below for practice:
Get hands-on with 1400+ tech skills courses.