Reputation: 43
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
Reputation: 15328
?-
bagof(X,childof(X,parent1),Xs).
Xs = [child1,child2,child3,child4].
?-
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