Prolog:如何获得输出的数量?
Prolog: How to get the number of output?
我有以下事实:
/* 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).
我试图让输出显示 parent 的 children 的数量。就我而言,我的 parent1 有 4 children。但是如何让输出显示数字“4”?
- 收集所有答案
?-
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.
把上面的打包成程序供以后使用re-use:
numberofchild(Parent, Count) :-
bagof(Child,childof(Child,Parent),Children),
length(Children,Count).
然后:
?- numberofchild(parent1, Count).
Count = 4.
注意没有children:
调用失败
?- numberofchild(foo, Count).
false.
或者如果 children 的数量不正确:
?- numberofchild(parent1, 444).
false.
我们可以列举:
?- numberofchild(Parent,Count).
Parent = parent1,
Count = 4 ;
Parent = parent2,
Count = 4.
我有以下事实:
/* 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).
我试图让输出显示 parent 的 children 的数量。就我而言,我的 parent1 有 4 children。但是如何让输出显示数字“4”?
- 收集所有答案
?-
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.
把上面的打包成程序供以后使用re-use:
numberofchild(Parent, Count) :-
bagof(Child,childof(Child,Parent),Children),
length(Children,Count).
然后:
?- numberofchild(parent1, Count).
Count = 4.
注意没有children:
调用失败?- numberofchild(foo, Count).
false.
或者如果 children 的数量不正确:
?- numberofchild(parent1, 444).
false.
我们可以列举:
?- numberofchild(Parent,Count).
Parent = parent1,
Count = 4 ;
Parent = parent2,
Count = 4.