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([Head | Tail], TotalSum) :-
TotalSum is Head + Sum1.
To run/test the above code, save it to a file called: list_sum.pl, fire-up your prolog interpreter and load it. In my case, I use swi-prolog. Here is the sample output:
% list_sum compiled 0.00 sec, 592 bytes
?- list_sum(, Sum).
Sum = 0 ;
?- list_sum([1,2,0,3], Sum).
Sum = 6 ;