Last active
July 31, 2017 21:00
-
-
Save GustavoCaso/5c27ddef55dc47488f8d9137a0f14cfa to your computer and use it in GitHub Desktop.
Flatten Exercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Flatten do | |
def flat(list) do | |
cond do | |
is_list(list) -> flat(list, []) |> Enum.reverse | |
true -> {:error, "Must pass a List"} | |
end | |
end | |
def flat([], acc), do: acc | |
def flat([h|t], acc) when is_list(h) do | |
flat(t, flat(h, acc)) | |
end | |
def flat([h|t], acc), do: flat(t, [h | acc]) | |
end | |
ExUnit.start() | |
defmodule FlattenTest do | |
use ExUnit.Case | |
test "returns tuple with error and reason" do | |
assert Flatten.flat("hello") == {:error, "Must pass a List"} | |
end | |
test "returns list if empty list passed" do | |
assert Flatten.flat([]) == [] | |
end | |
test "flats a nested list" do | |
assert Flatten.flat([1,[2],3,[4], [1,2,3]]) == [1,2,3,4,1,2,3] | |
end | |
test "flats really big nested list" do | |
assert Flatten.flat([1,[2],3,[4], [1,2,3], [3], [34, [5,5,6]]]) == [1,2,3,4,1,2,3,3,34,5,5,6] | |
end | |
test "flats even when empty list inside" do | |
assert Flatten.flat([[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]) == [1,2,3,4,5,6,7,8] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment