Find how many same objects exist
I have this code
co开发者_Python百科lor(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?
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).
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
精彩评论