Hingusan
Hingusan

Reputation: 43

Prolog: How to get the number of output?

I have the following facts:

/* facts */
parent(parent1, child1).
parent(parent2, child1).
parent(parent1, child2).
parent(parent2, child2).
parent(parent1, child3).
parent(parent2, child3).
parent(parent1, child4).
parent(parent2, child4).

/* rule */
childof(X, Y):- parent(Y ,X).

I am trying to make the output display the number of children of a parent. In my case, my parent1 have 4 children. But how I can make the output display the number '4'?

Upvotes: 0

Views: 139

Answers (1)

David Tonhofer
David Tonhofer

Reputation: 15328

  1. Collect all the answers
?- 
bagof(X,childof(X,parent1),Xs).

Xs = [child1,child2,child3,child4].
  1. Count them
?- 
bagof(X,childof(X,parent1),Xs),
length(Xs,Count).

Xs = [child1,child2,child3,child4],
Count = 4.

Pack the above into a procedure for later re-use:

numberofchild(Parent, Count) :-
   bagof(Child,childof(Child,Parent),Children),
   length(Children,Count).

Then:

?- numberofchild(parent1, Count).
Count = 4.

Note that the call fails if there are no children:

?- numberofchild(foo, Count).
false.

Or if the number of children stated is not correct:

?- numberofchild(parent1, 444).
false.

We can enumerate:

?- numberofchild(Parent,Count).
Parent = parent1,
Count = 4 ;
Parent = parent2,
Count = 4.

Upvotes: 2

Related Questions