Knowledge Base Count Prolog

I have something similar in my knowledge base:

number(1). number(3). number(6). number(8). number(9). number(12). 

Now I need a predicate that estimates the number of numbers in the knowledge base, for example:

 countnumbers(X). X = 6. 

How can i do this? please, I am new to the prologue and I cannot figure it out.

+4
source share
2 answers

Use findall/3 to get all the facts from your database, and then get the length of the list:

 countnumbers(X) :- findall(N, number(N), Ns), length(Ns, X). 

Be careful: number/1 may be an inline predicate.

+8
source

If you need to know how much X satisfied by some predicate, you do not need to know all of them. Using findall/3 really redundant in such tasks. When you have 6 or 606 of these X - this is not very important. But when you have a really big and heavy generator, you do not need to save all the values ​​in a list and then count the 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 is X", so the whole formula means something like "count the number X, which numberr(X) , and call that number Numbers .

So,

 ?- countNumbers(X). X = 6. 
+8
source

Source: https://habr.com/ru/post/1386331/


All Articles