O'Reilly logo

Programming Elixir 1.2 by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Build-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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required