Built-in Protocols

Elixir comes with the following protocols:

  • Enumerable and Collectable
  • Inspect
  • List.Chars
  • String.Chars

To play with these, let’s work with MIDI files.

A MIDI file consists of a sequence of variable-length frames. Each frame contains a four-character type, a 32-bit length, and then length bytes of data.[38]

We’ll define a module that represents the MIDI file content as a struct, because the struct lets us use it with protocols. The file also defines a submodule for the individual frame structure.

 defmodule​ Midi ​do
 
  defstruct(​content:​ <<>>)
 
 defmodule​ Frame ​do
  defstruct(
 type:​ ​"​​xxxx"​,
 length:​ 0,
 data:​ <<>>
  )
 
 def​ to_binary(%Midi.Frame{​type:​ type, ​length:​ length, ​data: ...

Get Programming Elixir ≥ 1.6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.