Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Finding Sum of A List



In this example, we will define a clause, list_sum(List, Sum), this will return the sum of the elements of the list.

  • If the list is empty, then sum will be 0.

  • Represent list as [Head|Tail], find sum of tail recursively and store them into SumTemp, then set Sum = Head + SumTemp.

Program (list_misc.pl)

 list_sum([],0). list_sum([Head|Tail], Sum) :- list_sum(Tail,SumTemp), Sum is Head + SumTemp. 

Output

 | ?- consult('D:/TP Prolog/Sample Codes/list_misc.pl'). compiling D:/TP Prolog/Sample Codes/list_misc.pl for byte code... D:/TP Prolog/Sample Codes/list_misc.pl compiled, 1 lines read - 646 bytes written, 4 ms (16 ms) yes | ?- list_sum([5,12,69,112,48,4],Sum). Sum = 250 yes | ?- list_sum([8,5,3,4,7,9,6,1],Sum). Sum = 43 yes | ?- 

Explanation

  • list_sum([],0). is the base case which states that sum of an empty list is 0.

  • list_sum([Head|Tail], Sum) :- list_sum(Tail,SumTemp), Sum is Head + SumTemp. represents the recursive call to get sum of elements of the list.

    • list_sum([Head|Tail], Sum) is to divide the list where Head, Y represents the first element of the list and Tail represents the rest of the list. Sum is the summation of elements of the list.

    • list_sum(Tail,SumTemp) calculates the sum of rest of the elements and store than in SumTemp.

    • Sum is Head + SumTemp evaluates and assign addition of Head and SumTemp and returns the sum of all elements in turn.

Advertisements