这些是我的事实:
married(man, widow).
married(father,daughter).
married(widow, man).
married(daughter,father).
parent(father, man).
parent(widow, daughter).
parent(man, bboy).
% here is the rule giving me problems,
parent(X,Y):-
married(Z,X),
parent(Z,Y).
当我运行parent(X,Y)时,它会无限地返回相同的答案
?- parent(X,Y).
X = father
Y = man ? ;
X = widow
Y = daughter ? ;
X = man
Y = bboy ? ;
X = widow
Y = bboy ? ;
X = widow
Y = daughter ? ;
X = widow
Y = bboy ? ;
X = widow
Y = daughter ? ;
如何阻止它重复,因为当另一个规则调用父规则时,它会使序言崩溃
答案 0 :(得分:0)
您的问题在这里:
parent(X,Y):-
married(Z,X),
parent(Z,Y).
实际上,如果删除married/2
,则可以更清楚地看到它:
parent(X,Y):-
parent(Z,Y).
这将导致无限递归。简单的事情是重命名规则或事实:
parent(father, man).
parent(widow, daughter).
parent(man, bboy).
parent_of(X, Y) :-
married(Z, X),
parent(Z, Y).
不再递归。