COM
COM

Reputation: 45

How to add all positive numbers in prolog

I am using swi-prolog to ge the sum of all positive integers in a given list

So far this is my code, Kindly assist me with where im going wrong

sumPos([] ,0).
sumPos([Head | Tail], X) :- Head > 0,
    sumPos(Tail, N), 
    X is N+Head.

To test i am using

sumPos([1,-2,3,-5], X).

And the answer should be X=4 but i get false

Upvotes: 1

Views: 293

Answers (2)

TA_intern
TA_intern

Reputation: 2422

You already got an answer but you can just use arithmetic to achieve the same without the if-then-else. Instead of:

X is N+Head

use:

X is N + max(Head, 0)

Here is your re-written predicate:

sumPos([] ,0).
sumPos([Head | Tail], X) :-
    sumPos(Tail, N), 
    X is N + max(Head, 0).

and here is your test:

?- sumPos([1,-2,3,-5], X).
X = 4.

Exercise: measure which implementation is faster in different Prologs, using different compilation flags, if available. How can you explain your results?

Upvotes: 0

Deffa
Deffa

Reputation: 184

You need another clause that is available when Head is negative:

sumPos([Head | Tail], X) :- Head =< 0, sumPos(Tail, X).

Upvotes: 5

Related Questions