Skip to content

Instantly share code, notes, and snippets.

@GusGA
Last active June 10, 2019 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GusGA/0e3cdc8d047c91c5d139ffe2aab14e3e to your computer and use it in GitHub Desktop.
Save GusGA/0e3cdc8d047c91c5d139ffe2aab14e3e to your computer and use it in GitHub Desktop.
Flatten implementation written in elixir without language helpers functions

Flatten elixir implementation

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment