Since a local variable head is defined in the quoted expression, the recursive call to the function overwrites the value of head in the expanded expression. This isn't a problem when quoting in the tail of the list , because head was already used to build as its head. :mindblown:
Here's the final implementation of recurse/1:
def recurse([h|t]) do
t = recurse(t)
quote do
[unquote(h)|unquote(t)]
end
endOutput as seen in code provided:
» mix test test/recursive_macro_test.exs
[3]
[2, 3]
[1, 2, 3]
.
Finished in 0.04 seconds (0.04s on load, 0.00s on tests)
1 test, 0 failures
Randomized with seed 9300
Output with implemention changed as commented:
» mix test test/recursive_macro_test.exs
[3]
[3, 3]
[3, 3, 3]
1) test recursive macro (RecursiveMacroTest)
test/recursive_macro_test.exs:23
Assertion with == failed
code: recursive([1, 2, 3]) == [1, 2, 3]
lhs: [3, 3, 3]
rhs: [1, 2, 3]
stacktrace:
test/recursive_macro_test.exs:24
Finished in 0.04 seconds (0.04s on load, 0.00s on tests)
1 test, 1 failure
Randomized with seed 812630