Elixir 練習問題 ListsAndRecursion-6

flattenn

defmodule MyList do
  def flatten(list) do
    _flatten(list, [])
  end
  defp _flatten([], r) do
    Enum.reverse(r)
  end
  defp _flatten([head|tail], r) do
    if is_list(head) do
      _flatten(tail, Enum.reverse(flatten(head)) ++ r)
    else
      _flatten(tail, [head | r])
    end
  end
end
^o^ > iex practice_10_2.exs
Eshell V8.0  (abort with ^G)
Interactive Elixir (1.3.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> MyList.flatten([1, [2, 3, [4] ], 5, [[[6]]]])
[1, 2, 3, 4, 5, 6]