我无法理解为什么我在 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.
这就是我想要的。
到目前为止,我只看到在进行递归时规则的顺序很重要。所以我不明白鲍勃为什么仍然是他自己的兄弟,只是因为我把差异检查放在了第一位。
谢谢你的帮助!