0
votes

I have to write a predicates that sums all the items in a list. The items can be a list with list of list in it. for example, sum1([1,[2,3],4,[5]],X). i have some code that SHOULD work, but is giving an arguments are not sufficiently instantiated error. I am very new to prolog but these look alright to me. here is my full code for this predicate (function)

suml([],0).
suml([H|T],X) :- atomic(H),S2 is H + X, suml(T,S2).
suml([H|T],X) :- suml(H,S1), S3 is S1 + X, suml(T,S3).
1

1 Answers

0
votes

Change the order of the following two conditions: S2 is H + X, suml(T,S2) and change the way you use is/2. Although this is logic programming, the order of the conditions in a rule matters. Put sum1(T, S2) first because you need S2 to be instantiated before computing the sum. Second, is arithmetically evaluates the right part and unifies it with the left part. So, you actually want to sum S2 and H to get X:

suml([H|T],X) :- atomic(H), suml(T,S2), X is H + S2.