sum of a list prolog code example
Example: Write a prolog program to find the sum of elements in given list.
domains
x = integer
l = integer*
predicates
sum(l,x)
clauses
sum([],0).
sum([X|List],Sum) :-
sum(List,Sum1),
Sum = X + Sum1.
Output :
Goal: sum([1,2,3,4],Sum)
Sum=10
1 Solution
Goal: sum([-2,-1,1,2],Sum)
Sum=0
1 Solution
Goal: sum([],Sum)
Sum=0
1 Solution
Goal: sum([1],Sum)
Sum=1
1 Solution