3

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?

mat
  • 40,498
  • 3
  • 51
  • 78
Src
  • 5,252
  • 5
  • 28
  • 56
  • 4
    First, you need to realize that, as a logical statement, `C = C + 1` does not make much sense. – repeat Dec 22 '15 at 20:58

1 Answers1

3

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.
repeat
  • 18,496
  • 4
  • 54
  • 166
  • 3
    I find it extremely valuable that you are posting such declarative solutions, thank you! It may seem repetitive, but on the other hand, contrast a few dozen posts with the vast amount of Prolog teaching material that does not contain a single grain of such methods, and from that see how much more is needed to provide the first traces of counterweight to the hitherto accumulated garbage! – mat Dec 22 '15 at 22:16
  • @mat. Thank you! I really appreciate it. Always focus on what we can do... bottom line: "I suggest that you deal with the issue on a going forward basis." http://dilbert.com/strip/1998-02-09 – repeat Dec 23 '15 at 00:01
  • Does this work with [`tcount/3`](http://stackoverflow.com/a/29960878/772868), too? – false Dec 23 '15 at 11:59