::Annie is here, arguing bitterly with herself::
When I gave the SWI-Prolog course a couple years ago I made this exercise, and included the
code below, with the explanation
in
double/2
we compute the value of HOut on the recursion down, but tack it onto the front of the output list on the way out. We save stack by using TCO .
Jason Rothfuss, one of my students, writes
The part I’m confused about is in bold about saving stack. I don’t see how stack can be saved here because you have to hold on to the HOut value until you’re on the way up/out. In other words, I don’t believe swipl can achieve TCO because the stack frame has a value that must be preserved to be used on the way up/out. Is that right, or am I missing something?
I agree with him, I guess (though at this point I’m baffled too).
Running the test, I see a spike in global but not in local.
So either this is doing TCO, or I’m misunderstanding the thread monitor output.
double([], []).
double([H|T], [HOut|TOut]) :-
HOut is 2 * H,
double(T, TOut).
test :-
findall(X, between(1, 1_000_000, X), List),
writeln('made list'),
sleep(3.0),
double(List, _).
::Annie is here, looking baffled::