Enumerable
Learn the Enumerable built-in protocol of Elixir.
We'll cover the following...
The Enumerable
protocol is the basis of all the functions in the Enum
module.
Any type implementing it can be used as a collection argument to Enum
functions.
We’re going to implement Enumerable
for our Midi
structure, so we’ll need to wrap the implementation in something like this:
defimpl Enumerable, for: Midi do
# ...
end
Major functions
The protocol is defined in terms of four functions: count
, member?
, reduce
, and slice
, as shown below:
defprotocol Enumerable do
def count(collection)
def member?(collection, value)
def reduce(collection, acc, fun)
def slice(collection)
end
The count
function returns the number of elements in the collection.
The member?
function is truthy if the collection contains value
. The reduce
function applies the given function to successive values in the collection and the accumulator; the value it reduces becomes the next accumulator. Finally, slice
is used to create a subset of a collection. Perhaps surprisingly, all the Enum
functions can be defined in terms of these four.
However, it isn’t that simple.
Maybe we’re using Enum.find
to find a value in a large collection. Once we’ve found it, we want to halt the iteration because continuing is pointless. Similarly, we may want to suspend an iteration and resume ...