1
votes

I'm trying to understand this sum predicate

 sum([], 0).
 sum([H|T], Sum) :-
    sum(T, Temp), 
    Sum is Temp + H.

It works however I don't understand why. From my understanding with a query such as sum([1,2,3], Sum) it will match on the second clause instantiating H as 1 and T as [2,3] and Sum is still Sum. Then it will attempt to satisfy the first sub goal calling sum again but in the second goal where Sum is Temp + H when is Temp given a value?

1

1 Answers

3
votes

Temp is given a value first in the base case, sum([],0). That causes Temp=0 in the recursive call above. The call above that adds H to give 0+H, etc.

To convince yourself of this, trace the execution of your query:

?- trace.
true.

[trace]  ?- sum([1,2,3], Sum).
   Call: (6) sum([1, 2, 3], _G376) ? creep
   Call: (7) sum([2, 3], _G455) ? creep
   Call: (8) sum([3], _G455) ? creep
   Call: (9) sum([], _G455) ? creep
   Exit: (9) sum([], 0) ? creep
^  Call: (9) _G460 is 0+3 ? creep
^  Exit: (9) 3 is 0+3 ? creep
   Exit: (8) sum([3], 3) ? creep
^  Call: (8) _G463 is 3+2 ? creep
^  Exit: (8) 5 is 3+2 ? creep
   Exit: (7) sum([2, 3], 5) ? creep
^  Call: (7) _G376 is 5+1 ? creep
^  Exit: (7) 6 is 5+1 ? creep
   Exit: (6) sum([1, 2, 3], 6) ? creep
Sum = 6.

(The creep is me hitting Enter; this is SWI-Prolog.)