nbonbon
nbonbon

Reputation: 1767

sumList predicate needs to check to see if their Sum is equal to the sum of all the elements in the list

I am implementing a method that when given Sum and a List. It will check to see that if you add the elements in the list, their sum is equal to the Sum given. Here is what I am trying to do thus far, but I am pretty sure it is wrong... I'm not really sure how to think about it.

  sumList([],0).
  sumList([X|Xrest], Sum) :-
     sumList[Xrest, Sum1),
     Sum is X + Sum1.

Could you give me a point in the right direction or at least let me know how to try to think about the problem?

Upvotes: 1

Views: 398

Answers (1)

It is all good with you code, except bracket in sumList[Xrest, Sum1).

So, this works pretty well in my swipl:

  sumList([],0).
  sumList([X|Xrest], Sum) :-
     sumList(Xrest, Sum1),
     Sum is X + Sum1.

?- sumList([1,2,3],X).
X = 6.

Upvotes: 1

Related Questions