Implement filter

I struggled a bit on this one, it took me two months!!!! jk

My assumption was that filter with an empty list does nothing, but actually, it returns an empty list. Second misunderstanding was that filter with tail doesn't need to be wrapped into another list. But hey, in the end I learned something!
This commit is contained in:
Nathan Mattes 2021-09-14 16:53:26 +02:00
parent ab927374b9
commit 1be7896f19
1 changed files with 14 additions and 0 deletions

View File

@ -30,7 +30,21 @@ defmodule MyEnum 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