Skip to content

Instantly share code, notes, and snippets.

@GustavoCaso
Last active July 31, 2017 21:00
Show Gist options
  • Save GustavoCaso/5c27ddef55dc47488f8d9137a0f14cfa to your computer and use it in GitHub Desktop.
Save GustavoCaso/5c27ddef55dc47488f8d9137a0f14cfa to your computer and use it in GitHub Desktop.
Flatten Exercise
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