Sum of elements in list in Prolog needs little explanation

prolog

Solution

This is the classic recursive approach - you need to get comfortable with it to understand Prolog.

Your rule has two clauses - the one for the empty list, and the one for a non-empty one. The empty list clause says that the sum of elements of an empty list is zero (which is perfectly reasonable). This is called "the base case of recursion". Every terminating recursive rule must have a base case.

The second clause is a little more complex. It says roughly this: "to compute the sum of elements in a non-empty list, first chop off the initial element, and compute the sum of elements in a shorter list that results. Call that sum `Sum1`. Now compute the `Total` by adding the value of the initial element to the value of `Sum1`.

The second clause recursively decomposes the list into a series of shorter lists until they get to an empty list. At this point the first clause steps in, providing the sum of an empty list.

Consider this example:

list_sum([12, 34, 56], X)
    list_sum([34, 56], <unknown-1>)
        list_sum([56], <unknown-2>)
            list_sum([], 0)         ---> succeeds with Total bound to 0
        <unknown-2> becomes 0 + 56  ---> succeeds with Total bound to 56
    <unknown-1> becomes 0 + 56 + 34 ---> succeeds with Total bound to 90
X becomes 0 + 56 + 34 + 12          ---> succeeds with X bound to 102

This works because each invocation level in the recursive chain gets its own variable for `Sum1`. These values start unbounded, but once the recursive invocation chain "bottoms out", `Sum1`s start getting values computed by each prior level. Eventually, the call chain reaches the top level, binding the final result to the variable passed by the caller.

Problem

I'm a beginner at prolog programming and I hope you humble and help me to pass this confusion I'm facing a problem to calculate the sum in prolog and I have the answer but it's not so clear to me. The answer is: ``` list_sum([], 0). list_sum([Head | Tail], Total) :- list_sum(Tail, Sum1), Total = Head + Sum1. ``` what I did not understand is what is the `Sum1` and how the program will work in steps it first will check the first condition `list_sum([], 0).` while the condition is not met it will divide the list into 2 parts `Head` and `Tail` then? I hope you accept a little beginner and give him some time to correct his confusing. Thanks you guys

Original source