Built-In Protocols

Elixir comes with the following protocols:

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

To play with these, we’ll implement a trivial datatype that represents the collection of 0s and 1s in an integer. The underlying representation is trivial:

 defmodule​ Bitmap ​do
  defstruct ​value:​ 0
 
  @doc ​"""
  A simple accessor for the 2^bit value in an integer
 
  iex> b = %Bitmap{value: 5}
  %Bitmap{value: 5}
  iex> Bitmap.fetch_bit(b,2)
  1
  iex> Bitmap.fetch_bit(b,1)
  0
  iex> Bitmap.fetch_bit(b,0)
  1
  """
 def​ fetch_bit(%Bitmap{​value:​ value}, bit) ​do
 use​ Bitwise
 
  (value >>> bit) &&& 1
 end
 end

The fetch_bit function uses the >>> and &&& functions in ...

Get Programming Elixir 1.3 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.