Swi Prolog:如何使用规则(不是查询)来计算元素的数量

Swi Prolog: how to count the number of elements by using rules (not query)

如标题所述,如何实现? 例如:

**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

我应该如何实施 number_of_child 规则? 我预期的答案是 Y 将显示 2(因为有 child 和 child2)或类似的东西。 谢谢。

您应该了解 setof/3bagof/3findall/3。它们是找到所有解决方案的通用序言谓词。

如果您想要一些 swi-prolog 特定的东西来计算解决方案,那么您可以使用 aggregate_all.

num_children(X, N) :- aggregate_all(count, child_of(X, _Y), N).

https://www.swi-prolog.org/FAQ/SingletonVar.html