Elixir basics · Lesson 21 (open contents)
Give different data one shared action
Define a protocol and implement it for two data types.
Run this first
Run it once, change one input, and compare the new result.
# 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"}.
Read from the first line down
- 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.
Symbols are not secret signs
defprotocolDeclare a shared operation.
defimpl ... for:Implement that operation for one type.
to_string/1Convert a value through the String.Chars protocol.
Match each name to its meaning
protocol
A protocol chooses an implementation from the type of its first argument.
implementation
defimpl supplies protocol behavior for one data type.
dispatch
Protocol dispatch selects the matching implementation at runtime.
Why these forms are useful
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.
Close the answer and try
Add a protocol implementation for Atom.
defimpl Readable, for: ____ do
def render(value), do: "atom=#{____}"
endTarget result: Readable.render(:ok) should return "atom=ok".
Stuck? Read one hint
Use Atom and Atom.to_string(value).
After you run it, see one answer
defimpl Readable, for: Atom do
def render(value), do: "atom=#{Atom.to_string(value)}"
endThink about it: Does a protocol dispatch on every argument?
No. Elixir protocols dispatch on the type of the first argument.
Remember these three lines
- 1
Protocols provide one action across types.
- 2
Each type owns an implementation.
- 3
Use protocols for data-type polymorphism, not process behavior.