Sum of elements in list in Prolog

Recently I noticed that my prolog skill is becoming rusty for not putting it work for very long. For this reason, I’m going to randomly write some prolog snippets here and there. Let’s started with one predicate called “sum_list” which calculate the value of all elements in a list.

% The sum of all elements in list in prolog

% empty list
list_sum([], 0).

list_sum([Head | Tail], TotalSum) :-
list_sum(Tail, Sum1),
TotalSum is Head + Sum1.

To run/test the above code, save it to a file called:, fire-up your prolog interpreter and load it. In my case, I use swi-prolog. Here is the sample output:

?. consult(list_sum).
% list_sum compiled 0.00 sec, 592 bytes

?- list_sum([], Sum).

Sum = 0 ;

?- list_sum([1,2,0,3], Sum).

Sum = 6 ;



9 thoughts on “Sum of elements in list in Prolog

  1. Please note that the sum_list predicate is not tail-recursive. It’s easy to make a tail-recursive variant with an accumulator, e.g.:

    sumlist(L,Sum) :-

    sumlist([H|T],Count,Sum) :-
    NewCount is Count + H,

    • Prolog works by saying ‘is this true and under what circumstances’.

      You give it a statement. In this case, for example:

      1. sumlist([5],X)

      Prolog can only say this is true, if it can produce this in it’s knowledgebase.

      We have one comparable statement. With Sum = X and L = [5], prolog can say that it’s true IF it can prove sumlist([5,4],0,X) is true

      2. This statement matches: sumlist([H|T],Count,Sum) with H = 5, T = [], Count = 0 and Sum = X.

      In order to prove this statement we need to proove the clauses that follow:
      NewCount = Count + H. So this sets NewCount as 5. In addition, with this value of NewCount we must also proove

      This equates to: sumlist([],5,Sum)

      3. This statement matcches sumlist([],Sum,Sum) with Sum = 5. We have said that this statement is true without any requirements. This means that Prolog has a valid set of inferences which return true, with our original parameter X = 5.

  2. Khng says:

    Hi,do you know how to count the element in all the list? Means, i got several list, each list got several element, i wan to count the total of all the list..

  3. Dinusha Suneth says:

    i got a IT assignment question which is asking calculate number of all Mobile base stations in operation..i dont know how to write a rule and predicate tht answer,,,,please help me,,,,

    %%%%%% mobile Base station in operation %%%%%%%%%


    (ex:number of mobile base stations = 5) like dat,,,,,,,please tell

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s