gpt4 book ai didi

prolog - Prolog 规则中目标(语句)的顺序

转载 作者:行者123 更新时间:2023-12-02 02:23:52 24 4
gpt4 key购买 nike

最近开始学习Prolog,遇到一个奇怪的问题。在这里您可以看到一个代码示例(我使用 SWI-Prolog 7.2.3),它给出了关系树和我的 2 个任务的解决方案。

/*   File:    ancestors.pl
Author: Dave Robertson
Purpose: Relationships in a family tree

Suppose we have a family tree like this :

alan andrea bruce betty eddie elsie fred freda
| | | | | | | |
|_____| |_____| |_____| |_____|
| | | |
clive clarissa greg greta
| |__________|___| | |
|__________|__| |_____________|
| | |
dave doris henry

which is defined in Prolog by the following 3 sets of predicates:

*/

% parent(Parent, Child).
% Parent is the parent of Child.

parent(alan, clive).
parent(andrea, clive).
parent(bruce, clarissa).
parent(betty, clarissa).
parent(clive, dave).
parent(clarissa, dave).
parent(clive, doris).
parent(clarissa, doris).
parent(eddie, greg).
parent(elsie, greg).
parent(fred, greta).
parent(freda, greta).
parent(greg, henry).
parent(greta, henry).

%% PROBLEM 1
%% How do you find out if someone is the ancestor of someone else ?
ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y).

%% PROBLEM 3
%% How do you know if someone is related to someone else ?
relative(X,Y) :- ancestor(X,Y).
relative(X,Y) :- ancestor(Y,X).
relative(X,Y) :- ancestor(Z,X), ancestor(Z,Y), X\==Y.

当我想找到戴夫的亲戚时,我会这样做:

relative(dave,X).
X = clive ;
X = clarissa ;
X = alan ;
X = andrea ;
X = bruce ;
X = betty ;
X = doris ;
X = doris ;
X = clive ;
X = doris ;
X = clive ;
X = doris ;
X = clarissa ;
X = doris ;
X = clarissa ;
X = doris ;
false.

然后我改变了相对的定义:

relative(X,Y) :-  ancestor(X,Y).
relative(X,Y) :- ancestor(Y,X).
relative(X,Y) :- X\==Y, ancestor(Z,X), ancestor(Z,Y).

我只是更改了最后一个语句中目标的顺序。现在我有以下输出:

relative(dave,X).

X = clive ;
X = clarissa ;
X = alan ;
X = andrea ;
X = bruce ;
X = betty ;
X = dave ;
X = doris ;
X = dave ;
X = doris ;
X = clive ;
X = dave ;
X = doris ;
X = clive ;
X = dave ;
X = doris ;
X = clarissa ;
X = dave ;
X = doris ;
X = clarissa ;
X = dave ;
X = doris ;
false.

我在输出中看到戴夫!这怎么发生的?我写了 X\== Y...有人能给我一个很好的解释吗?

还有一个问题。如何使我的程序不写出相同的答案?

谢谢!

最佳答案

(\==)/2 不是纯粹的关系,只能从操作上理解。如果您使用它,交换目标顺序可能会产生声明性错误的结果:

?- X \== Y, X = Y.X = Y.

请使用 dif/2 作为纯粹且完全声明性的方式来声明术语的不相等性。

?- dif(X, Y), X = Y.false.

参见了解更多信息。

关于prolog - Prolog 规则中目标(语句)的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33732576/

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