Search⌘ K
AI Features

Collectable

Understand how the Collectable protocol works in Elixir by learning its use with Enum.into. Discover how it enables building collections by defining initial values and adding elements, and how it supports working with complex data like MIDI streams. This lesson explains the protocol's role in managing collections functionally and efficiently.

We'll cover the following...

Introduction

We’ve already seen Enum.into. It takes something that’s enumerable and creates a new collection from it:

iex> 1..4 |> Enum.into([])
[1, 2, 3, 4]
iex> [ {1, 2}, {"a", "b"}] |> Enum.into(%{}) 
%{1 => 2, "a" => "b"}

The target of Enum.into must implement the Collectable protocol. This defines a single function, somewhat confusingly also called into. This function returns a two-element tuple. The first element is the initial value of the target collection. The second is a function to be called to add each item to the collection. ...