Skip to content

Instantly share code, notes, and snippets.

@g33kidd
Last active May 18, 2016 19:47
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 g33kidd/54e9ffcfa226695630a14fe7246b7067 to your computer and use it in GitHub Desktop.
Save g33kidd/54e9ffcfa226695630a14fe7246b7067 to your computer and use it in GitHub Desktop.
Array Flatten
# Elixir is by far one of my Favorite programming languages so I decided to write this Flattener in Elixir.
# It may look similar to Ruby, but it most definitely is not Ruby.
defmodule Flattener do
def flatten([]), do: []
# Takes the list head and adds the tail to the end of the list
# this gets repeated for each nested list inside the list and
# keeps adding the tail of each list to the end of the flattened list.
def flatten([h|t]), do: flatten(h) ++ flatten(t)
def flatten(h), do: [h]
end
# Map of lists to Enumerate over and test.
lists = %{
first: [[1,2,[3]],4,[5,6,[7]]],
second: [1,2,[3,[4,5]],6,[7,8,[9]]],
last: [[[1],2,3,[4,5,6]],7,[8,9,10,[11]]]
}
# Enumerate each list in the Map, Flatten the list, and output to the console.
Enum.each(lists, fn({key, val}) ->
IO.inspect RC.flatten(val)
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment