Created
July 23, 2021 03:13
-
-
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.
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 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