Last active
March 20, 2018 13:54
-
-
Save nicooga/b660fbf21993f042fd9b48024836a057 to your computer and use it in GitHub Desktop.
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 Flattening do | |
def flatten([]), do: [] | |
def flatten([head | tail]) when is_list(head), do: flatten(head) ++ flatten(tail) | |
def flatten([head | tail]), do: [head | flatten(tail)] | |
end | |
IO.inspect Flattening.flatten([[1,2,[3]],[4]]) | |
IO.inspect Flattening.flatten([[1,2,[3]],[4], [5]]) | |
IO.inspect Flattening.flatten([[1,2,[3]],[4], [5, [[6]]]]) | |
IO.inspect Flattening.flatten([[1,2,[3]],[4], [5, [[6]]], [7]]) | |
# We take advatange of Elixir's linked lists and pattern matching. | |
# Recursion will ensure any lists in the head get flattened. | |
# It will recurse over the root and any nested lists until | |
# the head is not a list and the tail is an empty list because we reached the last element. | |
# The recursion creates dynamic branching which makes it very hard to visualize what's happening. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment