I need some help with understanding the following Prolog source code:
addone([],[]).
addone([H|T],[H1|T1]):-H1 is H + 1, addone(T,T1).
This code, takes a given list and therefore prints out another one which has +1 added to each argument of it.
I don't understand how exactly this work, if I trace it:
[trace] 69 ?- addone([1,2,3],X).
Call: (6) addone([1, 2, 3], _G1196) ? creep
Call: (7) _G1273 is 1+1 ? creep
Exit: (7) 2 is 1+1 ? creep
Call: (7) addone([2, 3], _G1274) ? creep
Call: (8) _G1279 is 2+1 ? creep
Exit: (8) 3 is 2+1 ? creep
Call: (8) addone([3], _G1280) ? creep
Call: (9) _G1285 is 3+1 ? creep
Exit: (9) 4 is 3+1 ? creep
Call: (9) addone([], _G1286) ? creep
Exit: (9) addone([], []) ? creep
Exit: (8) addone([3], [4]) ? creep
Exit: (7) addone([2, 3], [3, 4]) ? creep
Exit: (6) addone([1, 2, 3], [2, 3, 4]) ? creep
X = [2, 3, 4].
I get to the point:
Call: (9) addone([], _G1286) ? creep
Exit: (9) addone([], []) ? creep
From here I don't understand how when I reach the base clause Prolog recalls its saved values?
Can you please explain me how this thing works, what is the logic behind it?
Thank you in advance, Petar!
Exit
is a return from a recursive call back to a point inaddone
where there were pending values/results. So you're seeing all those recursive calls finally return and the final results going in their place. – lurker