68 lines
1.3 KiB
Elixir
68 lines
1.3 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
|
|
|
|
# I gave up on these two.
|
|
# split
|
|
# take
|
|
end
|
|
|
|
defmodule MyList do
|
|
def flatten([]) do
|
|
[]
|
|
end
|
|
|
|
def flatten([head|tail]) do
|
|
# this is basically the recursion
|
|
flatten(head) ++ flatten(tail)
|
|
end
|
|
|
|
def flatten(head) do
|
|
# if there's only on element, we make a list out of it, so that we can concat them
|
|
[head]
|
|
end
|
|
end
|