This script to be executed requires elixir to be installed
To run this script execute $ elixir flatten.exs
The output should be something like this:
$ elixir flatten.exs
.
Finished in 0.02 seconds (0.02s on load, 0.00s on tests)
1 test, 0 failures
| defmodule Flatten do | |
| @moduledoc """ | |
| List flatten recursive implementation without language helpers | |
| """ | |
| @doc """ | |
| Flat a nested list of list. | |
| Returns list flattend. | |
| ## Examples | |
| iex> Flatten.flatten([1,[2],[3,4]]) | |
| [1, 2, 3, 4] | |
| """ | |
| def flatten(list) do | |
| flatten(list, []) |> reverse([]) | |
| end | |
| def flatten([], accum), do: accum | |
| def flatten([[]| tail], accum), do: flatten(tail, accum) | |
| def flatten([[_|_] = head|tail], accum), do: flatten(tail, flatten(head, accum)) | |
| def flatten([head|tail], accum), do: flatten(tail, [head | accum]) | |
| def reverse([], accum), do: accum | |
| def reverse([head | tail], accum), do: reverse(tail, [head | accum]) | |
| end | |
| ExUnit.start() | |
| defmodule FlattenTest do | |
| use ExUnit.Case | |
| setup do | |
| list_to_flatten = [ | |
| [1, [2], [3, 4]], | |
| [[1, 2], [3], 4], | |
| [1, 2, 3, [4]], | |
| [[1], [2], [3], [4]], | |
| [[1], 2, 3, [4]], | |
| [1, [2, 3], 4], | |
| [[1, 2, 3], [4]], | |
| [1, 2, [3, 4]], | |
| [[1, 2], [3, 4]], | |
| [[1], 2, 3, 4], | |
| [[1, 2, 3, 4]], | |
| [[1], [2, 3, 4]] | |
| ] | |
| [list_to_flatten: list_to_flatten] | |
| end | |
| test "Flatten a list of list", context do | |
| Enum.each(context[:list_to_flatten], fn(list) -> | |
| assert Flatten.flatten(list) == [1, 2, 3, 4] | |
| end) | |
| end | |
| end | |