Programming Elixir 1.6 exercise solutions - Lists and Recursion-5

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.

@pragdave

There is another error.

    if fun.(head) do
      [head | filter(tail, fun)]
  def filter([], _fun), do: []

  def filter([head | tail], fun) do
    if fun.(head) do
      [head | filter(tail, fun)]
    else
      filter(tail, fun)
    end
  end

Sorry, I’m being dense. Could you explain where the problem is?

The problem is this line
[ head, filter(tail, fun) ]
should be changed to
[head | filter(tail, fun)]