0

I have this code

color(blue).
color(red).
color(blue).
color(green).

I want to make a rule that will count how many times the X color exists. For this case count_color(X) should return 2.

Is that possible in this way or i have to make a list with the colors?

false
  • 10,264
  • 13
  • 101
  • 209
anom
  • 1
  • 4
    Do you mean that after calling `count_color(blue, X)`, `X` should be 2? – svick May 28 '11 at 19:01
  • This question covers the same ground as [this earlier one](http://stackoverflow.com/questions/6060268/prolog-count-the-number-of-times-a-predicate-is-true), which presents a method of solution not yet described here (assert/retract) besides the two which are. – hardmath May 31 '11 at 01:25

2 Answers2

2

aggregate/3 does not exist in ISO prolog, so it's not available in all implementations. But you can get the same result using findall/3, as in:

count_color(Color, N) :- findall(_, color(Color), List), length(List, N).
Jerome
  • 2,350
  • 14
  • 25
1

It is possible by using the aggregate/3 predicate:

count_color(Color, N) :- aggregate(count, color(Color), N).

A pointer for using aggregate/3: aggregate/3 in swi-prolog

Community
  • 1
  • 1
pad
  • 41,040
  • 7
  • 92
  • 166