我最近开始研究 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... 谁能给我一个很好的解释?
还有一个问题。如何让我的程序不写相同的答案?
谢谢!