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
