Glen Takahashi
Glen Takahashi

Reputation: 881

checking if sum of list is value in prolog

I'm trying to write a simple predicate that will determine if all the elements of a list add up to a sum, but I don't understand why mine isn't working.

It seems like it should work, but when i do list_sum([1,2,3],X) it returns no, or list_sum([1,2,3],6) it also returns null. Any ideas?

list_sum([],0).
list_sum([F], V) :- F=V.
list_sum([F|R], V) :- list_sum(R, V-F).

Upvotes: 0

Views: 348

Answers (2)

list_sum([],0).
list_sum([V], V).
list_sum([F,G|R], V) :- S is F + G, list_sum([S|R], V).

Upvotes: 3

CapelliC
CapelliC

Reputation: 60014

Arithmetic must be explicitly evaluated. Try

list_sum([], 0).
list_sum([F|R], V) :- list_sum(R, S), V is S+F.

Upvotes: 1

Related Questions