0

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.

ZonG
  • 77
  • 5

1 Answers1

2

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

rajashekar
  • 3,460
  • 11
  • 27
  • Thank you for giving me some ideas and this successfully meet my expectation. Though, the variables have a little bit problem. For my case it should be num_children(X, N) :- aggregate_all(count, child_of(X,N), N). as Y is recognized as unknown variable by the swi prolog program. Thank you again for giving me some ideas. – ZonG Jun 11 '21 at 04:41
  • @ZonG: No you should use `child_of(X, _Y)` to suppress the warning. While `child_of(X, N)` works it is not an accurate portrayal of what is happening. Let me edit my answer. – rajashekar Jun 11 '21 at 04:49
  • I see, thank you for explaining. Can you explain more about why 'child_of(X, N)' is not accurate despite it shows same answer as 'child_of(X, _Y)' does? – ZonG Jun 11 '21 at 04:52
  • It is a bit complicated. Go through this if you have time https://stackoverflow.com/questions/64716106/unusual-behaviour-of-findall – rajashekar Jun 11 '21 at 04:54