gpt4 book ai didi

序言:一个人是他自己的 sibling ?

转载 作者:行者123 更新时间:2023-12-04 11:53:14 26 4
gpt4 key购买 nike

我在理解为什么我在 prolog 中的代码根据我放置规则的顺序做某事时遇到了一些麻烦。

这是我的数据库:

parent(tom, bob).
parent(tom, liz).
parent(mary, bob).
parent(mary, liz).

male(tom).
male(bob).
female(mary).
female(liz).

以下是规则:
%difference(X, Y) ==> Predicate to check if two people X and Y are not the same person.
difference(X, Y) :- \==(X, Y).
father(X, Y) :- male(X), parent(X, Y), difference(X, Y).
mother(X, Y) :- female(X), parent(X, Y), difference(X, Y).
sibling(X, Y) :-
difference(X, Y),
mother(M, X), mother(M, Y),
father(F, X), father(F, Y).

问题是,当我这样做时,
?- sibling(bob, X).

我得到
X = bob ;
X = liz ;
false.

但是当我改变顺序时(我在最后一部分放了差异(X,Y))
sibling(X, Y) :-
mother(M, X), mother(M, Y),
father(F, X), father(F, Y),
difference(X, Y).

我打电话
?- sibling(bob, X).

我得到
X = liz;
false.

这就是我想要的。

到目前为止,我只看到在进行递归时规则的顺序很重要。
所以我不明白鲍勃怎么仍然是他自己的 sibling ,因为我先做了差异检查。

谢谢你的帮助!

最佳答案

这是因为统一的工作方式。如果将差异放在首位,则 X 和 Y 的值尚未统一为任何值。考虑跟踪:

 goal list: [sibling(bob, Z)]
goal: sibling(bob, Z).
X-> bob, Y -> Z
goal list: [difference(bob, Y), mother(M, bob), mother(M, Y), father(F, bob), father(F, Y).]
goal: difference(bob, Y) --SUCCESS
goal list: [mother(M, bob), mother(M, Y), father(F, bob), father(F, Y).]
goal: mother(M, bob)
...

当您最后调用差异时,X 和 Y 已统一,如果它们是相同的值,差异将失败。然后会发生回溯。

使用 prolog 环境的跟踪功能查看执行过程中逐步发生的情况。

关于序言:一个人是他自己的 sibling ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20223390/

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