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.

1 Answer 1

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

4
  • 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, 2021 at 4: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, 2021 at 4: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, 2021 at 4:52
  • It is a bit complicated. Go through this if you have time stackoverflow.com/questions/64716106/…
    – rajashekar
    Jun 11, 2021 at 4:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.