Reputation: 109
I have the following Prolog fact to sum the positive numbers from a list but it´s not working. What am I doing wrong?
somarPositivos([],0).
somarPositivos([H|T],Soma):-H>0,somarPositivos(T,Soma1),Soma is Soma1+H.
somarPositivos([H|T],Soma):-H=<0 ,somarPositivos(T,Soma1).
Upvotes: 0
Views: 618
Reputation: 18663
You have a typo in the third clause. It should be:
somarPositivos([H|T],Soma):-H=<0 ,somarPositivos(T,Soma).
Most Prolog compilers would print a warning that the variables Soma
and Soma1
are singleton variables in that clause.
Some notes on programming style following Prolog coding guidelines. Indent your code. Use spaces around operators. Use underscores instead of camelCase for predicate names for readbility. Thus, preferably write:
somar_positivos([],0).
somar_positivos([H|T],Soma) :-
H > 0,
somar_positivos(T,Soma1),
Soma is Soma1+H.
somar_positivos([H|T],Soma) :-
H =< 0,
somar_positivos(T,Soma).
As an improvement to this initial version of the predicate, can you rewrite it to make it tail-recursive using an accumulator?
Upvotes: 2