I am starting Prolog, courtesy of Seven Languages in Seven Weeks, and struggling a bit with understanding how Prolog is handling recursion.
Given the following code:
sum(0, []). sum(Total, [Head|Tail]) :- sum(Sum,Tail), Total is Head + Sum. % executed in the Prolog interpreter: sum(X, [1,2,3]) X = 6 I understand what this code is doing, but I am a little hung up on how the Prolog is resolving the recursive calls of sum. Mainly, it is strange to me that there is no explicit "return" within sum.
My understanding is that something like this happens:
A. The interpreter attempts to unify the rule sum(X, [1,2,3]) by calling sum:
0 Sum(X, [1, 2, 3]) 1 Sum(Y, [2,3] 2 Sum(Z, [3]) 3 Sum(0, []) % our recursive base B. Once we hit the base fact, it climbs back up the recursive "stack":
3 Sum(0, []), Total = 0 % we start at our base fact 2 Sum(1, [3]), Total = 3 1 Sum(2, [2, 3]), Total = 5 0 Sum(X, [1, 2, 3]) Total = 6 % sweet, sweet unification Is my understanding of how this is functioning correct? Or is there a better way for my imperative mind to think about/express what is going on above?