The provided solutions have a few typos or errors, this one in particular tipped me over into submitting errata:
defmodule MyList do
def filter([], _fun), do: []
def filter([ head | tail ], fun) do
if fun.(head) do
[ head, filter(tail, fun) ]
else
[ filter(tail, fun) ]
end
end
end
The else
block will result in nested lists instead of a single list.
See my test of the function here:
iex(11)> require Integer
iex(12)> MyList.filter([1,2,3], &Integer.is_even/1)
[[2, [[]]]]
It should be:
# ...
else
filter(tail, fun)
end
If exercise solutions are fair game, I’d be happy to submit more errata.