gpt4 book ai didi

prolog - 如何在 Prolog 中找到目标的所有解决方案?

转载 作者:行者123 更新时间:2023-12-03 22:18:32 24 4
gpt4 key购买 nike

我有谓词 P1 一个接一个地返回值,如下所示:

-? P1(ARGUMENTS, RETURN).
-? RETURN = 1;
-? RETURN = 2;
-? RETURN = 3;
-? fail.

我还有另一个谓词 P2:
P2(ARGUMENTS, LIST) :- P1(ARGUMENTS, RETURN),... % SOMEHOW HERE I NEED TO INSERT ALL VALUES OF RETURN TO LIST.

如何找到 RETURN 的所有值并将它们分配给 LIST ?

最佳答案

使用 findall 要做到这一点:

P2(ARGUMENTS, LIST) :- findall(X, P1(ARGUMENTS, X), LIST).

这与 bagof function mentioned in the question 有关由安德斯林达尔链接。关于这两个函数(和第三个函数 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

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 - 如何在 Prolog 中找到目标的所有解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1468150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com