ZonG
ZonG

Reputation: 77

Swi Prolog: how to count the number of elements by using rules (not query)

As title stated above, how to make this possible? For example:

**Facts:**
parent(child, parent).

parent(child, parent2).

parent(child2, parent).

parent(child2, parent2).

**Rules:**
childof(X,Y) :- parent(Y, X).  
number_of_child(X,Y):- X has Y number of child

How should I implement the number_of_child rules? My expected answer is Y will show 2 (since there are child and child2) or something like that. Thank you.

Upvotes: 0

Views: 685

Answers (1)

rajashekar
rajashekar

Reputation: 3753

You should learn about setof/3, bagof/3 and findall/3. They are general prolog predicates to find all solutions.

If you want something swi-prolog specific just to count the solutions then you can use aggregate_all.

num_children(X, N) :- aggregate_all(count, child_of(X, _Y), N).

https://www.swi-prolog.org/FAQ/SingletonVar.html

Upvotes: 2

Related Questions