Skip to content

Instantly share code, notes, and snippets.

@sheharyarn
Created September 3, 2018 22:08
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 sheharyarn/22d5271f02d7afd1dbd1bc3b75002d95 to your computer and use it in GitHub Desktop.
Save sheharyarn/22d5271f02d7afd1dbd1bc3b75002d95 to your computer and use it in GitHub Desktop.
Flatten a List in Elixir (Custom Implementation)
defmodule Flatten do
@doc """
Flattens a List in Elixir
## Examples
```
Flatten.flatten([1,2,3,4])
# => [1,2,3,4]
Flatten.flatten([1,[2,3],4])
# => [1,2,3,4]
Flatten.flatten([[1, []], [2, [3,4], [[5]]], [[]], 6, [[], 7]])
# => [1,2,3,4,5,6,7]
```
"""
@spec flatten(List.t) :: List.t
def flatten(list) do
list
|> Enum.reduce([], &do_flatten/2)
|> Enum.reverse
end
# Private Helper
# Recursively flatten all items in reverse
# (Reverse the entire list at the end in the calling method)
defp do_flatten(nested, acc) when is_list(nested) do
Enum.reduce(nested, acc, &do_flatten/2)
end
defp do_flatten(item, acc) do
[ item | acc ]
end
end
ExUnit.start
defmodule FlattenTest do
use ExUnit.Case, async: true
@moduledoc """
To run tests directly:
$ elixir -r flatten.exs flatten_test.exs
"""
describe "#flatten" do
test "it works for empty lists" do
assert Flatten.flatten([]) == []
end
test "it works for lists without nesting" do
assert Flatten.flatten([1,2,3,4,5]) == [1,2,3,4,5]
end
test "works for lists with one-level nesting" do
assert Flatten.flatten([1,[2,3],4]) == [1,2,3,4]
end
test "it works for lists with multi-level nesting" do
assert [1,2,3,4,5,6,7] ==
Flatten.flatten([[1, []], [2, [3,4], [[5]]], [[]], 6, [[], 7]])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment