Created
April 27, 2016 17:40
-
-
Save rhnonose/27dc0b58eba625f47ef4667220478f2c to your computer and use it in GitHub Desktop.
List.flatten reimplementation in elixir.
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 MyList do | |
def flatten(array) do | |
reduce_flatten(array, []) | |
end | |
def reduce_flatten([], acc), do: acc | |
def reduce_flatten([elem | rest], acc) do | |
Enum.reduce([elem | rest], acc, &reduce_flatten/2) | |
end | |
def reduce_flatten(elem, acc) do | |
acc ++ [elem] | |
end | |
end |
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 MyListTest do | |
use ExUnit.Case | |
doctest MyList | |
test "flatten empty array" do | |
assert MyList.flatten([]) == [] | |
end | |
test "flattened array stays unchanged" do | |
assert MyList.flatten([1,2,3]) == [1,2,3] | |
end | |
test "flatten simple nested" do | |
assert MyList.flatten([1,[2],3]) == [1,2,3] | |
end | |
test "flatten messy nested array" do | |
assert MyList.flatten([[[],[2,3,[4]]], [5,6], [[[7]]]]) == [2,3,4,5,6,7] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment