liveBook · Manning

Collectable

As explained in Elixir in Action, Third Edition

The Collectable protocol is an Elixir protocol that defines how values are repeatedly added to a resulting data structure.

Collectable is an Elixir protocol for repeatedly adding values to a resulting data structure. Comprehensions and Enum.into/2 can target lists, maps, MapSet, file streams, or custom collectable types. section 3.4.4 section 4.3.3

A Collectable implementation supplies:

  • into/1, which returns the original structure and an appender function. section 4.3.3
  • A {:cont, entry} branch that adds each value. section 4.3.3
  • A :done branch that returns the completed structure and a :halt branch for cancellation. section 4.3.3

Collecting into a custom to-do list

Implementing Collectable for TodoList lets Enum.into(entries, TodoList.new()) transfer enumerable entries into the custom structure. section 4.3.3

defimpl Collectable, for: TodoList do                   #1
  def into(original) do                                 #1
    {original, &into_callback/2}                        #1
  end
 
  defp into_callback(todo_list, {:cont, entry}) do      #2
    TodoList.add_entry(todo_list, entry)                #2
  end                                                   #2
                                                        #2
  defp into_callback(todo_list, :done), do: todo_list   #2
  defp into_callback(_todo_list, :halt), do: :ok        #2
end

The callback implementation shows how continuation, completion, and cancellation instructions drive collection. section 4.3.3

How Elixir in Action, Third Edition covers it

How deep it goes
Defines the protocol callbacks and their control instructions, then stops short of broader implementation details.
Examples
Uses multiplication-table maps and a custom TodoList as collectable targets.
What it assumes
Assumes familiarity with comprehensions and enumerable values while teaching the callback protocol from its implementation.
What you can do after
Build it from scratch by implementing Collectable for a custom data structure.
How it connects
Connects comprehensions and Enum.into/2 with protocols, Enumerable, Enum, Stream, maps, lists, and custom data structures.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.