Skip to content

Instantly share code, notes, and snippets.

@marciol
Created July 23, 2021 03:13
Show Gist options
  • Save marciol/58ba9e67124466d9166934d4f463d0c5 to your computer and use it in GitHub Desktop.
Save marciol/58ba9e67124466d9166934d4f463d0c5 to your computer and use it in GitHub Desktop.
After a long time without working with Elixir, I was studying Clojure and did a implementation of flatten, so I did the same with Elixir.
defmodule Flatten do
def flatten(list, holding_list \\ [], flattened \\ [])
def flatten([[h | t] | rest], holding_list, flattened) do
flatten(h, [t, rest | holding_list], flattened)
end
def flatten([h | t], holding_list, flattened) do
flatten(t, holding_list, [h | flattened])
end
def flatten([], [h | holding_list], flattened) do
my_flatten(h, holding_list, flattened)
end
def flatten(x, [h | holding_list], flattened) do
flatten(h, holding_list, [x | flattened])
end
def my_flatten([], [], flattened) do
flattened
|> Enum.reverse()
|> IO.inspect(label: :flattened)
end
end
ExUnit.start()
defmodule FlattenTest do
use ExUnit.Case
test "must flatten the list" do
# require IEx
# IEx.pry()
assert Flatten.flatten([[1, 2], [3, [4, [5, 6]]]]) == [1, 2, 3, 4, 5, 6]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment