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: list_sum.pl, fire-up your prolog interpreter and load it. In my case, I use swi-prolog. Here is the sample output: ...

February 4, 2007 · 1 min · 133 words · kenno