Skip to content

Instantly share code, notes, and snippets.

@rhnonose
Created April 27, 2016 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhnonose/27dc0b58eba625f47ef4667220478f2c to your computer and use it in GitHub Desktop.
Save rhnonose/27dc0b58eba625f47ef4667220478f2c to your computer and use it in GitHub Desktop.
List.flatten reimplementation in elixir.
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
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