I have recently started learning prolog, but I'm having a hard time with recursive rules. I understand the simple rules but I'm having trouble with this example I found of a program that gives the sum of all elements in a list:
addup([], 0).
addup([FirstNumber | RestOfList], Total) :-
addup(RestOfList, TotalOfRest),
Total is FirstNumber + TotalOfRest.
Now if I trace this, I get the following:
[trace] ?- addup([3, 5, 7], Total).
Call: (7) addup([3, 5, 7], _G322)
Call: (8) addup([5, 7], _L1)
Call: (9) addup([7], _L2)
Call: (10) addup([], _L3)
Exit: (10) addup([], 0) % I understand what it does till here
^ Call: (10) _L2 is 7+0
^ Exit: (10) 7 is 7+0
Exit: (9) addup([7], 7)
^ Call: (9) _L1 is 5+7
^ Exit: (9) 12 is 5+7
Exit: (8) addup([5, 7], 12)
^ Call: (8) _G322 is 3+12
^ Exit: (8) 15 is 3+12
Exit: (7) addup([3, 5, 7], 15)
Total = 15.
I understand the first few steps; it keeps cutting the head of and making new TotalOfRest's untill the original list is empty and it matches with the first fact. That makes the third TotalOfRest (I called it _L3) equal to 0. But what now? How does prolog make the step that L2 is equal to 7 + 0. I understand that prolog starts backtracking, but what matches with what to reach that conclusion? Is Total now 7? Or are there three different Total's with different values's like with TotalOfRest? And is RestofList still equal to [] and FirstNumber still 7?
So basically: how does prolog go from having figured out L3 to the end conclusion?
I'm very new to this so if anyone could explain it for me really slowly, I would appreciate it so much!