如何在 Prolog 中找到目标的所有解决方案? [英] How do I find all solutions to a goal in Prolog?
问题描述
我有谓词 P1,它一个接一个地返回值,如下所示:
I have predicate P1 that returns values one after the other like this:
-? P1(ARGUMENTS, RETURN).
-? RETURN = 1;
-? RETURN = 2;
-? RETURN = 3;
-? fail.
我还有另一个谓词 P2:
I also have another predicate called P2:
P2(ARGUMENTS, LIST) :- P1(ARGUMENTS, RETURN),... % SOMEHOW HERE I NEED TO INSERT ALL VALUES OF RETURN TO LIST.
如何找到RETURN
的所有值并将它们分配给LIST
?
How do find all of the values of RETURN
and assign them to LIST
?
推荐答案
使用 findall
来完成这个:
Use findall
to accomplish this:
P2(ARGUMENTS, LIST) :- findall(X, P1(ARGUMENTS, X), LIST).
这与bagof
有关由 Anders Lindahl 链接的问题 中提到的功能.关于这两个函数(以及第三个函数setof
)之间的关系有很好的解释这里:
This is related to the bagof
function mentioned in the question linked to by Anders Lindahl. There is a good explanation on the relationship between the two functions (and a third function setof
) here:
为了说明差异,请考虑一个小例子:
To illustrate the differences consider a little example:
listing(p).
p(1,3,5).
p(2,4,1).
p(3,5,2).
p(4,3,1).
p(5,2,4).
尝试以下目标.(答案显示已被修改以保存空间.)
Try the following goals. (The answer displays have been modified to save space.)
?- bagof(Z,p(X,Y,Z),Bag).
Z = _G182 X = 1 Y = 3 Bag = [5] ;
Z = _G182 X = 2 Y = 4 Bag = [1] ;
Z = _G182 X = 3 Y = 5 Bag = [2] ;
Z = _G182 X = 4 Y = 3 Bag = [1] ;
Z = _G182 X = 5 Y = 2 Bag = [4] ;
No
?- findall(Z,p(X,Y,Z),Bag).
Z = _G182 X = _G180 Y = _G181 Bag = [5, 1, 2, 1, 4] ;
No
?- bagof(Z,X^Y^p(X,Y,Z),Bag).
Z = _G182 X = _G180 Y = _G181 Bag = [5, 1, 2, 1, 4] ;
No
?- setof(Z,X^Y^p(X,Y,Z),Bag).
Z = _G182 X = _G180 Y = _G181 Bag = [1, 2, 4, 5] ;
No
谓词bagof
和setof
yield个人绑定的集合目标中的自由变量.setof
产生一个排序的版本没有重复的集合.至避免绑定变量,使用存在量词表达式.为了例如目标bagof(Z,X^Y^p(X,Y,Z),Bag)
要求Z
的袋子使得存在一个 X
并且存在一个 Y
使得p(X,Y,Z)
".findall
就像 bagof
自动带有所有自由变量存在量化.此外findall
在那里返回一个空列表 []
是没有目标满意度,而 bagof
失败.
The predicates bagof
and setof
yield
collections for individual bindings of
the free variables in the goal. setof
yields a sorted version of the
collection without duplicates. To
avoid binding variables, use an
existential quantifier expression. For
example the goal
bagof(Z,X^Y^p(X,Y,Z),Bag)
asks for
"the Bag of Z
's such that there exists
an X
and there exists a Y
such that
p(X,Y,Z)
". findall
acts like bagof
with all free variables automatically
existentially quantified. In addition
findall
returns an empty list []
there
is no goal satisfaction, whereas bagof
fails.
这篇关于如何在 Prolog 中找到目标的所有解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!