Skip to content

Instantly share code, notes, and snippets.

@joseph-lozano
Created November 4, 2018 00:43
Show Gist options
  • Save joseph-lozano/e8fc2aaf3b419901e35cf288f73fccd8 to your computer and use it in GitHub Desktop.
Save joseph-lozano/e8fc2aaf3b419901e35cf288f73fccd8 to your computer and use it in GitHub Desktop.
defmodule Flatten do
@spec flatten(List.t()) :: List.t()
def flatten([]), do: []
def flatten([head | tail]) when is_list(head), do: flatten(head) ++ flatten(tail)
def flatten([head | tail]), do: [head | flatten(tail)]
def flatten(_), do: raise("argument must be a list")
end
ExUnit.start()
defmodule FlattenTest do
import Flatten
import ExUnit.Assertions, only: [assert_raise: 2]
use ExUnit.Case
test "returns an empty array" do
assert flatten([]) == []
end
test "returns an array of one element" do
assert flatten(["a"]) == ["a"]
end
test "returns an array of two elements" do
assert flatten(["a", "b"]) == ["a", "b"]
end
test "can flatten one element" do
assert flatten([["a"]]) == ["a"]
end
test "raises on non list argument" do
assert_raise RuntimeError, fn -> flatten("foo") end
end
test "big lists work too" do
assert flatten([[1, 2, 3], [4, [[5, 6], [7], 8]], 9, 10, [[[[[11]]]]]]) == Enum.to_list(1..11)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment