A question on recursion, Look at the recursive function below that takes a list of lists as input.
during the recursion the subsequent input will get reduced to [ [] | tail_values ] or [ head_values | [] ] - What I observed is that the VM never calling the method defined for input matching [ head_values | [] ]
What is the best way to solve this scenario ? I have pasted a working and non working input below the method definition.
defmodule Transpose do
def transpose(input) do
_transpose(input)
end
defp _transpose([]) do
IO.puts("ONE!!!")
[]
end
defp _transpose([[] | []]) do
IO.puts("TWO!!!")
[]
end
defp _transpose([[] | tail]) do
IO.puts("THREE!!!")
[tail]
end
defp _transpose([head | []]) do
IO.puts("FOUR!!!")
[head]
end
defp _transpose(input) do
IO.inspect(input)
[Enum.map(input, &hd/1) | _transpose(Enum.map(input, &tl/1))]
end
end
IO.puts("**********method call below worked as expected*************")
# This function call worked fine - reached function that prints "THREE!!!"
IO.inspect Transpose.transpose([["A", "B"], ["C", "D", "E"]])
IO.puts("\n\n**********Method call below Did not work as expected*************")
# This function Failed - I was expectign this to reach the function that prints "FOUR!!!"
IO.inspect Transpose.transpose([["A", "B", "C"], ["D", "E"]])
replacing “|” with comma introduced another problem. Now I can’t have more than two elements in the list after adding comma.
#this will fail unless another function is added like this
#defp _transpose([[],[],[]]), do: [] and so on .... for every increment.
IO.inspect Transpose.transpose([["A","B"], ["C","D"], ["E","F"]])
[tail] would match any list with exactly one element and bind that elements value to tail, [[] | tail] though will match any list which has at least one element. This element has to match the empty list. The remaining elements are bound to tail.