Skip to content

Instantly share code, notes, and snippets.

@ospatil
Last active July 23, 2016 23:18
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 ospatil/744611085cd870787fe2e1188e6212cf to your computer and use it in GitHub Desktop.
Save ospatil/744611085cd870787fe2e1188e6212cf to your computer and use it in GitHub Desktop.
Intuition into recursion as alternative to loops in FP
defmodule P7 do
# public function that calls a private one with accumulator
def flatten(list), do: Enum.reverse(do_flatten(list, []))
# base case - empty list
defp do_flatten([], result), do: result
# next two clauses for list with many elements
defp do_flatten([head | tail], result) when is_list(head), do: do_flatten(tail, do_flatten(head, result))
defp do_flatten([head | tail], result), do: do_flatten(tail, [head | result])
end
ExUnit.start
defmodule P7Test do
use ExUnit.Case
test "P7.flatten" do
# step 1 - empty list
assert P7.flatten([]) == []
# step 2 - list with single element - either list or value
assert P7.flatten([1]) == [1]
assert P7.flatten([[1]]) == [1]
assert P7.flatten([[[1]]]) == [1]
# step 3 - list with many elements - either list or value
assert P7.flatten([[1, [2, 3]], 4, [5, 6]]) == [1, 2, 3, 4, 5, 6]
assert P7.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