elixir-book/maps/myenum.exs

51 lines
1.0 KiB
Elixir

defmodule MyEnum do
# all?/1
# Returns true if all elements in enumerable are truthy.
def all?([head|tail]) do
# head truthy and all tail
(head != false) and (head != nil) and all?(tail)
all?([head|tail], fn elem -> (elem != false) and (elem != nil) end)
end
def all?([]) do
all?([], nil)
end
def all?([head|tail], fun) do
fun.(head) and all?(tail, fun)
end
def all?([], _fun) do
true
end
# each/2
# Invokes the given fun for each element in the enumerable.
def each([head|tail], fun) do
fun.(head)
each(tail, fun)
end
def each([], _fun) do
:ok
end
# Filters the enumerable, i.e. returns only those elements for which fun returns a truthy value.
def filter([], _fun) do
# do nothing -> This is wrong. Return an empty array instead.
[]
end
# filter using if ... do ... else ... end
def filter([head|tail], fun) do
if fun.(head) do
[head|filter(tail, fun)]
else
filter(tail, fun)
end
end
# split
# take
end