Last active
July 23, 2016 23:18
-
-
Save ospatil/744611085cd870787fe2e1188e6212cf to your computer and use it in GitHub Desktop.
Intuition into recursion as alternative to loops in FP
This file contains hidden or 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 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