Search code examples
listprologclpfdvisual-prolog

Prolog: Count positive elems in list


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?


Solution

  • The following code uses on , so don't expect it to run as-is on :-(
    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".

    1. count_pos([], 0).

      The number of positive arithmetic expressions contained in the empty list [] is zero.

    2. 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.

    3. 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.