Member-only story
Implement Enumerable in Elixir
Today, we will learn how to implement the Enumerable
protocol in Elixir.
For those of you who live under a rock, Elixir is an awesome functional language. And protocols are a way of having polymorphism (as there are no classes in functional languages, polymorphism is not really a thing) allowing one to inject behaviour into a module.
Let’s imagine that we have a struct called Company
. Companies have a name
and a list of employees
(which, in this example, gets initialized to an empty list).
defmodule Company do
defstruct [:name, employees: []]
end
Say, we would want to have this struct implement the Enumerable
protocol so that we could create a Company
and use Enum.count
to get the number of employees
that work in this Company
or for example use Enum.map
so that we can transform the employees
of the Company
.
Let’s start!
There are four functions which we would need to implement to fully support all functions of the Enumerable
module:
- count/1
- member?/2
- reduce/3
- slice/1
That’s it!
count/1
Let’s first tackle the easiest one of the four: count/1.