Member-only story

Implement Enumerable in Elixir

Dunya Kirkali
4 min readMay 9, 2023

Photo by Karine Avetisyan on Unsplash

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Dunya Kirkali
Dunya Kirkali

Written by Dunya Kirkali

I'm an engineering manager passionate about empowering engineers to deliver exceptional work through collaboration and innovation.

No responses yet

Write a response