我需要计算所有X
持有some_predicate(X)
的东西,而且确实有很多这样的X
. 最好的方法是什么?
第一条线索是findall
,累积到一个列表并返回列表的长度。
countAllStuff( X ) :-
findall( Y
, permutation( [1,2,3,4,5,6,7,8,9,10], Y )
, List
),
length( List, X ).
(permutation/2
只是一个虚拟占位符,表明有很多结果并且计算计数的方法很糟糕)
显然,对于真实数据,会有堆栈溢出。
?- countAllStuff( X ).
ERROR: Out of global stack
然后,我试图用 替换findall
,setof
但无济于事。
最后,我找到了 [ aggregate
][1] (可点击的)谓词系列,并尝试使用aggregate/3
and aggregate/4
:
?- aggregate(count, permutation([1,2,3,4], X), Y ).
X = [1, 2, 3, 4],
Y = 1 .
?- aggregate(count, [1,2,3,4], permutation([1,2,3,4], X), Y ).
X = [1, 2, 3, 4],
Y = 1 ;
X = [1, 2, 4, 3],
Y = 1 ;
一切都错了,我想。我需要得到这样的东西:
?- aggregate(count, permutation([1,2,3,4], X), Y ).
Y = 24 .
我究竟做错了什么?
我如何声明一个谓词来计算正确的答案?[1]:http ://www.swi-prolog.org/pldoc/doc/home/vnc/prolog/lib/swipl/library/aggregate.pl