The protocols of the standard library

The everyday calls of Elixir are thin layers over protocols. IO.inspect/1 asks the value how to print itself, interpolation asks it how to become text, Enum.into/2 asks the target how to collect values, and the functions of Enum ask the source how to be enumerated. This lesson names the four protocols and shows a type plugged into two of them.

Inspect behind IO.inspect

Inspect decides how a value is written for a developer. The default implementation shows a struct with its module name and its fields; a defimpl replaces it for one type. The struct below prints as an amount and a currency instead:

inspect.exs

defmodule Money do defstruct [:amount, :currency] end defimpl Inspect, for: Money do def inspect(%Money{amount: amount, currency: currency}, _opts) do "#{amount} #{currency}" end end IO.inspect(struct(Money, %{amount: 10, currency: "EUR"}))

elixir inspect.exs

10 EUR

The second argument of the callback is the set of options IO.inspect/2 passes, such as limit: or pretty:; the implementation above ignores it. The derivation from the protocols lesson, @derive {Inspect, only: [:x]}, is the same protocol with an implementation the compiler writes.

String.Chars behind interpolation

String.Chars decides how a value becomes text. Interpolation, string concatenation with <> and to_string/1 all call to_string/1 of this protocol, which is why a value can enter a sentence once its implementation exists:

stringchars.exs

defmodule Money do defstruct [:amount, :currency] end defimpl String.Chars, for: Money do def to_string(%Money{amount: amount, currency: currency}) do "#{amount} #{currency}" end end money = struct(Money, %{amount: 10, currency: "EUR"}) IO.puts("the price is #{money}") IO.puts(to_string(money))

elixir stringchars.exs

the price is 10 EUR
10 EUR

The two lines are the same call from two places: interpolation and to_string/1. A type without the implementation cannot enter a string, which is the mistake of the last section. The protocol is also what makes IO.puts/1 accept a value: a binary passes through and anything else is converted.

Collectable behind into:

Enum.into/2 takes an enumerable and a target, and the target decides how to collect the values through the Collectable protocol. A map collects key-value pairs and a list collects values, and the call reads the same for both:

into.exs

pairs = [{"b", 2}, {"a", 1}] IO.inspect(Enum.into(pairs, %{})) IO.inspect(Enum.into([1, 2, 3], []))

elixir into.exs

%{"a" => 1, "b" => 2}
[1, 2, 3]

A map has no order, so the keys print in the order the display chooses; the list keeps the order it was given. The for comprehension uses the same protocol with its into: option, and a program that collects into a custom struct implements Collectable for it.

Enumerable behind Enum

Enum.map/2, Enum.filter/2 and Enum.reduce/3 do not know what a list is. They call the Enumerable protocol of the value, and that protocol provides a reduce, a count, a membership test and a slice. A list, a map, a range and a stream all implement it, which is why one function works over all of them. Implementing it by hand is a job for a library type, not a first lesson; the point here is that the function you call is a protocol call.

Access is the fifth protocol a beginner meets: it is what get_in/2 and put_in/2 use to follow a path, and the nested access lesson shows why a struct needs Access.key!/1 there.

The mistake: interpolating a map

A map has no String.Chars implementation, so it cannot go into a string. The compiler accepts the interpolation and the program stops at run time with a Protocol.UndefinedError that names the type:

nochars.exs

IO.puts("value: #{%{a: 1}}")

elixir nochars.exs

** (Protocol.UndefinedError) protocol String.Chars not implemented for Map

Got value:

    %{a: 1}

    (elixir 1.19.7) lib/string/chars.ex:7: String.Chars.impl_for!/1
    (elixir 1.19.7) lib/string/chars.ex:26: String.Chars.to_string/1
    nochars.exs:1: (file)

The fix is inspect/1 for a value a developer reads, or a field of the map for a value a user reads. The error is a deliberate design choice: a map has no natural text form, and a language that guessed one would print the wrong thing in a log or a message. The protocols lesson shows the defimpl that gives a type the text form it deserves.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which protocol decides how IO.inspect/1 writes a value?

    Answer

    Inspect

    IO.inspect/1 calls the Inspect implementation of the value.

  2. Which protocol turns a value into text for interpolation?

    Answer

    String.Chars

    Interpolation and to_string/1 call String.Chars.to_string/1.

  3. Which protocol does Enum.into/2 use for its target?

    Answer

    Collectable

    The target collects the values, which is the job of Collectable.

  4. Which protocol do the functions of Enum call?

    Answer

    Enumerable

    Enum.map/2 and its neighbours enumerate the source through Enumerable.

  5. What does this program print? defmodule Money do defstruct [:amount, :currency] end defimpl Inspect, for: Money do def inspect(%Money{amount: amount, currency: currency}, _opts) do "#{amount} #{currency}" end end IO.inspect(struct(Money, %{amount: 10, currency: "EUR"}))

    Answer

    10 EUR

    The custom Inspect writes the amount and the currency, without the struct syntax.

  6. What does this program print? defmodule Money do defstruct [:amount, :currency] end defimpl String.Chars, for: Money do def to_string(%Money{amount: amount, currency: currency}) do "#{amount} #{currency}" end end money = struct(Money, %{amount: 10, currency: "EUR"}) IO.puts("the price is #{money}")

    Answer

    the price is 10 EUR

    Interpolation uses the String.Chars implementation of the struct.

  7. What does this program print? pairs = [{"b", 2}, {"a", 1}] IO.inspect(Enum.into(pairs, %{}))

    Answer

    %{"a" => 1, "b" => 2}

    The map collects the pairs and prints its keys in the order of the display.

  8. What does this program print? IO.inspect(Enum.into([1, 2, 3], []))

    Answer

    [1, 2, 3]

    A list collects the values in the order it receives them.

  9. What does this program do? IO.puts("value: #{%{a: 1}}")

    Answer

    A Protocol.UndefinedError: String.Chars is not implemented for Map

    A map has no text form through String.Chars, so the run stops before printing.

  10. What should a program call to print a map for a developer?

    Answer

    inspect/1, or IO.inspect/1

    inspect/1 is the developer form; String.Chars is the user form and has no map implementation.

Автор статьи: Arthur Isaev