Well, you are making progresses, but there are still things that won’t really work in this code.
First of all, the first definition of cross
, for empty lists, returns 0
. I don’t know what you are trying to do (are you implementing zip
?), but that seems at odd with the rest of the program. What is your expected output? If you are using recursion, your base clause should return that.
Second, the tuple {h1, h2}
is created but never used nor returned, so right now it is useless. If you are implementing zip
, you’ll want to accumulate these tuples to finally return them in a list.
Remember that Elixir functions always return the result of their last expression.
Also, t1
and t2
are already lists. If you wrap them in brackets you will get nested lists, which is probably not what you want.
Here’s a nudge in the right direction:
defmodule Ans0 do
# In the public 2 argument version you can call a private
# 3 arguments version with an added argument to accumulate
# step by step the final result
def cross(a, b) do
cross(a, b, [])
end
defp cross([], [], accumulated) do
# I leave this to you, reason on what must be returned
# when you reach the base case
end
defp cross([head1 | tail1], [head2 | tail2], accumulated) do
# Here we prepend {head1, head2} to the accumulated
# result, and pass it with the tails of the lists to the next
# iteration
cross(tail1, tail2, [{head1, head2} | accumulated])
end
end
When implementing it, pay attention to the order of the accumulated list, and also beware that this implementation would only work if the list arguments have the same length. You can add base cases to account for different lengths (I leave this to you).
In general, my recommendation is that you take your time to learn the basics of Elixir before you jump into recursion exercises: it will make it easier to understand why something is not working as it should.