Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Prolog 序言无限重复相同的答案_Prolog_Infinite Loop - Fatal编程技术网

Prolog 序言无限重复相同的答案

Prolog 序言无限重复相同的答案,prolog,infinite-loop,Prolog,Infinite Loop,以下是我的事实: 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

以下是我的事实:

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 ? ;
我如何阻止它重复,因为当另一个规则调用父规则时,它会崩溃prolog

您的问题就在这里:

parent(X,Y):-
    married(Z,X),
    parent(Z,Y).
实际上,如果删除
已婚/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).
不再递归