序言:一个人是他自己的兄弟姐妹? [英] Prolog: a person is a sibling of himself?

查看:50
本文介绍了序言:一个人是他自己的兄弟姐妹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解为什么我在 prolog 中的代码会根据我放置规则的顺序执行某些操作.

I'm having some trouble understanding why my code in prolog does something based on the order I put my rules in.

这是我的数据库:

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))

But when I change the ordering (I put difference(X, Y) at the last part)

sibling(X, Y) :-
    mother(M, X), mother(M, Y),
    father(F, X), father(F, Y),
    difference(X, Y).

我打电话给

?- sibling(bob, X).

我明白

X = liz;
false.

这就是我想要的.

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

So far, I've only seen that the ordering of the rules matter when doing recursion. So I don't understand how bob is still a sibling of himself just because I put the difference check first.

感谢您的帮助!

推荐答案

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

This is because of the way unification works. If you put difference first the values of X and Y are not yet unified to any values. Consider the trace:

 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 已统一,如果它们是相同的值,差异将失败.那么就会发生回溯.

When you put the difference call last, both X and Y have been unified and difference will fail if they are the same value. Then backtracking will occur.

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

Use the trace feature of your prolog environment to see what happens step by step during the execution.

这篇关于序言:一个人是他自己的兄弟姐妹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆