There is a tiny error in your program to start with - the line Total = Head + Sum
means that Total
is a structure +
with two arguments. You probably mean is
in place of =
meaning arithmetic evaluation. But the best is to use #=
instead.
In your question you are asking what the program will do. That is quite a reasonable question in command-oriented ("imperative") languages, because the only meaning you can get out of the program is its step-by-step action. But here in Prolog things are a bit different. You can still try to apply that step-by-step thinking but sooner or later you will realize that things can get extremely complex here, simply because Prolog has not one control-flow but two at the same time called (AND- and OR-control). And even the "data-structures" are different...
But there is a way to read a Prolog program, that has no counterpart in imperative languages: You can understand a program as a relation between the arguments. In this manner, you can concentrate on what the relation looks like instead on procedural aspects. After all, if the relation described is wrong, there is no point in asking how the program does this.
So let me rephrase your program:
:- use_module(library(clpfd)).
list_sum([], 0).
list_sum([E|Es], S) :-
S #= E+T,
list_sum(Es, T).
it first will check the first condition list_sum([], 0). while the condition is not met it will divide the list into 2 parts H and T then ?
Your question implies that there is a single control flow ("while is such typical construct that implies it"). But it might also work differently. Consider the query:
?- list_sum(Xs,0).
Xs = []
; Xs = [0]
; Xs = [_A,_B], _A+_B#=0
; ... .
Here we ask What lists exists whose sum is 0. Now your "while" no longer makes sense.
The answers we get are: The empty list ; a list with 0
; a two-element list where the sum of the elements is 0 ; etc...
The best way to understand such programs is to read them as relations like so:
list_sum([], 0
: An empty list has sum 0.
The rule now reads best in the direction of the arrow :-
that is, right-to-left:
list_sum(Es, T).
: *Provided Es
is a list with sum T
and ...
S #= E+T
: ... S
is E
plus T
...
:-
... then we can conclude that ...
list_sum([E|Es], S)
: S
is the sum of the list [E|Es]
.
In this manner these things can be understood without referring too much to procedural details. There is more to it like understanding termination see failure-slice.