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
contains C
positive arithmetic expressions
and if some arithmetic expression E
is not positive
then conclude that [E|Es]
also contains C
positive arithmetic expressions.
count_pos([E|Es], C) :- E #> 0, C #= C0+1, count_pos(Es, C0).
If list Es
contains C0
positive arithmetic expressions
and if some arithmetic expression E
is positive
then conclude that [E|Es]
also contains C0+1
positive arithmetic expressions.
Sample query:
?- count_pos([1,2,3,0,-1,-2], C).
C = 3
; false.