简体   繁体   English

用递归规则编写序言? “错误:超出本地堆栈”

[英]Writing prolog with recursive rules? “ERROR: Out of local stack”

Given facts such as: 给定事实,例如:

  • Jake is smarter than Nik 杰克比尼克更聪明
  • Nik is smarter than Wes Nik比Wes聪明
  • Wes is smarter than Dik Wes比Dik聪明

Write a recursive program that will determine that Jake's is smarter than Dik's. 编写一个递归程序,确定Jake比Dik更聪明。

The solution that I have is: 我拥有的解决方案是:

smarter(jake, nik).
smarter(nik, wes).
smarter(wes, dik).
smarter(X, Y) :-
    smarter(X, Z),
    smarter(Z, Y).

The output: 输出:

?- smarter(jake, dik).
True

but when I swap it: 但是当我交换它时:

?- smarter(dik, jake)

The output will show "ERROR: Out of local stack" I need the output to show "False". 输出将显示“ ERROR:Out of local stack”。我需要输出以显示“ False”。 How do I fix it? 我如何解决它?

Thanks 谢谢

Your code can prove 您的代码可以证明

        ?- smarter(jake, dik).

because using X = jake, Y = dik it founds a Z=nik such that smarter(jake,nik) (this is a fact) and then smarter(nik,dik), (this is proved considering X1=nik, Y1=dik, Z1=wes). 因为使用X = jake,Y = dik会找到一个Z = nik,使得smarter(jake,nik)(这是事实)然后smarter(nik,dik)(考虑到X1 = nik,Y1 = dik被证明,Z1 = wes)。

However, in order to prove 但是,为了证明

       ?- smarter(dik, jake).

with X =dik, Y=jake, prolog needs a Z such that smarter(dik, Z). 当X = dik,Y = jake时,序言需要一个Z以便更聪明(dik,Z)。 However, there is no fact smarter(dik, Z). 但是,没有更聪明的事实(dik,Z)。 Then, the rule is applied again ... and you have the loop. 然后,再次应用规则...,您便有了循环。

The idea to fix (at least this particular example) is to distinguish facts and rules: 要解决的想法(至少是此特定示例)是区分事实和规则:

isSmarter(jake, nik).
isSmarter(nik, wes).
isSmarter(wes, dik).

smarter(X, Y) :- isSmarter(X,Y).

smarter(X, Y) :-
    isSmarter(X, Z),
    smarter(Z, Y).

This should work. 这应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM