i want to count positive elements in list (VIsual Prolog). So i wrote this function:
positiveCount([], C).
positiveCount([A], C) :- A > 0, C = C + 1.
positiveCount([H|T], C) :- H > 0,!,C = C+1,positiveCount(T,C); positiveCount(T,C).
Error:
The flow pattern '(o,i)' does not exist for '+' main.pro
AS i understood from this error, i can't use C=C+1
for C as input variable.
Any ideas how can i fix my code?
The following code uses clpfd on swi-prolog, so don't expect it to run as-is on visual-prolog:-(
Still, I hope it is of use to you!
:- use_module(library(clpfd)). count_pos([], 0). count_pos([E|Es], C) :- E #=< 0, count_pos(Es, C). count_pos([E|Es], C) :- E #> 0, C #= C0+1, count_pos(Es, C0).
Let's read the clauses in plain English in the direction of the "arrow" :-
, that is "right to left".
count_pos([], 0).
The number of positive arithmetic expressions contained in the empty list
[]
is zero.
count_pos([E|Es], C) :- E #=< 0, count_pos(Es, C).
If list
Es
containsC
positive arithmetic expressions
and if some arithmetic expressionE
is not positive
then conclude that[E|Es]
also containsC
positive arithmetic expressions.
count_pos([E|Es], C) :- E #> 0, C #= C0+1, count_pos(Es, C0).
If list
Es
containsC0
positive arithmetic expressions
and if some arithmetic expressionE
is positive
then conclude that[E|Es]
also containsC0+1
positive arithmetic expressions.
Sample query:
?- count_pos([1,2,3,0,-1,-2], C).
C = 3
; false.