AvicT
AvicT

Reputation: 21

Sum only the positive elements in a list in prolog

How do i only sum all the positive numbers?

sumlist([],0).
sumlist([H|T],N):-sumlist(T,N1),N is N1 +H.

?- sumlist([-2,2,3],N).
   N = 3, unexpected.
   N = 5. % expected

Upvotes: 1

Views: 134

Answers (3)

TessellatingHeckler
TessellatingHeckler

Reputation: 29003

In SWI Prolog, include the numbers which 0 is less than into list Ps, then sum Ps:

?- include(<(0), [-2,-1,0,1,2], Ps),
    sum_list(Ps, Sum).

Sum = 3

Upvotes: 1

brebs
brebs

Reputation: 4438

Another method:

plus_positive(N, Sum, Sum1) :-
    (   N > 0 ->
        plus(N, Sum, Sum1)
    ;   Sum1 = Sum
    ).
    
sum_positive(Lst, Sum) :-
    foldl(plus_positive, Lst, 0, Sum).

Result in swi-prolog:

?- sum_positive([-2, 2, -4, 3, -8], Sum).
Sum = 5.

Upvotes: 0

damianodamiano
damianodamiano

Reputation: 2662

There are many solutions, here two possible, the former with tail recursion, the latter without tail recursion.

sum_positive([],S,S).
sum_positive([H|T],ST,S):-
    (   H > 0 -> ST1 is ST + H ; ST1 = ST),
    sum_positive(T,ST1,S).

sp([],0).
sp([H|T],S):-
    sp(T,S1),
    (   H > 0 ->  S is H + S1 ; S = S1).

?- sp([1,2,3,-2],S).
S = 6
?- sum_positive([-2,1,12,-4],0,S).
S = 13

Upvotes: 0

Related Questions