A typical loop code in Prolog is something like:
loop_test :-
format('loop...~n'),
loop_test.
as discussed in another question: How Can I simulate a while loop in Prolog with unchangeable conditions?
Here's my question: Is this recursive form safe against overflow? Typically such a recursive code of C,C++,Python would overflow as in each function call a new stack is added. I executed above loop_test
under trace
. It was something like:
?- trace.
?- loop_test.
Call: (6) loop_test2 ? creep
Call: (7) format('loop...~n') ? creep
loop...
Exit: (7) format('loop...~n') ? creep
Call: (7) loop_test2 ? creep
Call: (8) format('loop...~n') ? creep
...
loop...
Exit: (158) format('loop...~n') ? creep
Call: (158) loop_test2 ? creep
Call: (159) format('loop...~n') ? creep
...
Clearly the number is increasing.
With this simple code, I couldn't find the memory increase; I executed loop_test
for more than 5 min and tracked VmPeak (peak size of virtual memory) written in /proc/xxx/status, but no change was observed.
I want to understand if the above code (loop_test
) is really safe? and Why is it safe? (or safer way to implement loops in Prolog).
Many thanks.