我正在用Prolog编写一个家谱程序。以下是我的规则:
father(X,Y):-male(X),parent(X,Y).
mother(X,Y):-female(X),parent(X,Y).
parent(X, Y) :- father(X, Y).
parent(X, Y) :- mother(X, Y).
ancestor(X,Y):-parent(X,Y).
ancestor(X,Y):-parent(X,Z),ancestor(Z,Y).
grandfather(X,Y):-male(X),parent(X,Z),parent(Z,Y).
grandMother(X,Y):-female(X),parent(X,Z),parent(Z,Y).
sibling(X,Y):-parent(Z,X),parent(Z,Y),X = Y.
cousin(X,Y) :-ancestor(Z,X),ancestor(Z,Y),not(parent(Z,X)),not(parent(Z,X)),not(ancestor(X,Y)),not(ancestor(Y,X)).
但是,每当我查询"祖先"时,我都会收到错误:
1815KB of Code Space (025D0000--02795D90)
Current hole: 4FE40000--80040000
%
% PC: user:parent/2 at clause 1
% Continuation: prolog:$do_yes_no/2 at clause 2
% 512KB of Global Stack (029C2000--02A4207C)
% 1265384KB of Local Stack (02A55E4C--4FE10000)
% 0KB of Trail (4FE10004--4FE10044)
% Performed 1 garbage collections
% All Active Calls and
% Goals With Alternatives Open (Global In Use--Local In Use)
%
% user:parent/2 (512KB--1265384KB)
% user:parent/2 (512KB--1265384KB)...
% ...user:parent/2 (512KB--1265377KB)
% .....
ERROR!!
RESOURCE ERROR- not enough stack
这也给"表亲"规则带来了问题,它给出了
%
%
% YAP OOOPS: likely bug in YAP, segmentation violation.
%
%
我的"祖先"规则可能做错了什么?
假设有一个事实:
male(adam).
如果现在查询:
parent(adam,cain).
然后它将评估:
parent(adam,cain) :-
father(adam,cain).
现在father/2
将进一步评估:
parent(adam,cain) :-
father(adam,cain) :-
male(adam),
parent(adam,cain).
所以我们看到它被困在一个无限循环中:为了验证/接地parent/2
,它是用parent/2
来定义的,但没有级数:我们用完全相同的参数来调用它。
所以Prolog将陷入这个无限循环。由于ancestor/2
取决于parent/2
,因此它的症状与parent/2
相同。
尝试删除循环依赖关系。