Last active
December 20, 2015 18:38
-
-
Save tomodutch/9f5a6242da6896c1301d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule CustomEnum do | |
defstruct items: [] | |
end | |
defimpl Enumerable, for: CustomEnum do | |
@doc """ | |
Return the amount of items | |
##Examples | |
iex> Enum.count %CustomEnum{items: []} | |
0 | |
iex> Enum.count %CustomEnum{items: [1, 2, 3]} | |
3 | |
""" | |
def count(enum) do | |
{:ok, count_size(enum)} | |
end | |
defp count_size(%CustomEnum{items: []}), do: 0 | |
defp count_size(enum = %CustomEnum{items: [_|tail]}) do | |
%{enum | items: tail} | |
|> count_size | |
|> Kernel.+(1) | |
end | |
@doc """ | |
Return whether an element is a member of items | |
##Examples | |
iex> Enum.member? %CustomEnum{items: []}, 1 | |
false | |
iex> Enum.member? %CustomEnum(items: [1, 2, 3]), 1 | |
true | |
""" | |
def member?(enum, elm) do | |
{:ok, contains?(enum, elm)} | |
end | |
defp contains?(%CustomEnum{items: []}, _), do: false | |
defp contains?(%CustomEnum{items: [elm|_]}, elm), do: true | |
defp contains?(enum = %CustomEnum{items: [_|tail]}, elm) do | |
%{enum | items: tail} | |
|> contains? elm | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment