Skip to content

Instantly share code, notes, and snippets.

@pietrofxq
Created July 2, 2019 22:51
Show Gist options
  • Save pietrofxq/4612b5c3c4e22e4b5e022f17fc79051b to your computer and use it in GitHub Desktop.
Save pietrofxq/4612b5c3c4e22e4b5e022f17fc79051b to your computer and use it in GitHub Desktop.
defmodule Flatten do
@moduledoc """
Documentation for Flatten.
"""
@doc """
Flatten an array. Ignore nil and empty list values
## Examples
iex> Flatten.flatten([1, 2, [3], [4, 5, [6, 7, 8, [9, 10]]]])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
"""
@spec flatten(list(integer)) :: list(integer)
def flatten(list), do: flatten(list, [])
defp flatten([head | tail], acc) when is_nil(head) or head == [], do: flatten(tail, acc)
defp flatten([head | tail], acc) when is_list(head), do: flatten(head, flatten(tail, acc))
defp flatten([head | tail], acc), do: [head | flatten(tail, acc)]
defp flatten([], acc), do: acc
end
defmodule FlattenTest do
use ExUnit.Case
doctest Flatten
test "flattens array" do
assert Flatten.flatten([[1, 2, [3]], 4]) == Enum.to_list(1..4)
end
test "empty list returns empty list" do
assert Flatten.flatten([]) == []
end
test "ignores empty list and nil values" do
assert Flatten.flatten([nil, [], [], nil, 1]) == [1]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment