If you need to know how many X
satisfied some predicate you don't need to know all of them. Using of findall/3
is really redundant in tasks like that. When you have 6 or 606 these X
- it's not a big deal of course. But when you have really large and heavy generator - you don't need to keeping all values in list and then counting it length.
Aggregate
solves this problem well:
numberr(1).
numberr(3).
numberr(6).
numberr(8).
numberr(9).
numberr(12).
countNumbers( Numbers ) :-
aggregate( count, X^numberr( X ), Numbers ).
X^
means "there exists X", so the whole formula means something like "count the number X that numberr(X)
and call that number Numbers
.
So
?- countNumbers(X).
X = 6.