Give different data one shared action: full examples and further reading
The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.
Define a protocol and implement it for two data types.
Render an integer and a list through the same Readable.render/1 call.
Run this first
Run it once, change one input, and compare the new result.
Original full example
# Give integers and lists one shared rendering API
defprotocol Readable do
def render(value)
end
defimpl Readable, for: Integer do
def render(value), do: "number=#{value}"
end
defimpl Readable, for: List do
def render(value), do: "items=#{length(value)}"
end
{Readable.render(7), Readable.render([:a, :b])}The result is {"number=7", "items=2"}.
Steps for the full example
- Read
defprotocol: Declare a shared operation. - Read
defimpl ... for:: Implement that operation for one type. - Read
to_string/1: Convert a value through the String.Chars protocol.
Original lesson notes
Run the example first. Predict one result, then change one input and run it again.
A protocol chooses an implementation from the type of its first argument.
defimpl supplies protocol behavior for one data type.
Symbols and terms
defprotocol- Declare a shared operation.
defimpl ... for:- Implement that operation for one type.
to_string/1- Convert a value through the String.Chars protocol.
- protocol
- A protocol chooses an implementation from the type of its first argument.
- implementation
defimplsupplies protocol behavior for one data type.- dispatch
- Protocol dispatch selects the matching implementation at runtime.
Original full exercise
Add a protocol implementation for Atom.
Exercise starter
defimpl Readable, for: ____ do
def render(value), do: "atom=#{____}"
endReadable.render(:ok) should return "atom=ok".
Show hint
Use Atom and Atom.to_string(value).
Show original answer
Reference answer
defimpl Readable, for: Atom do
def render(value), do: "atom=#{Atom.to_string(value)}"
endDoes a protocol dispatch on every argument?
No. Elixir protocols dispatch on the type of the first argument.
Original lesson takeaways
- Protocols provide one action across types.
- Each type owns an implementation.
- Use protocols for data-type polymorphism, not process behavior.