Prolog:超出本地堆栈错误

时间:2016-11-19 15:52:18

标签: prolog failure-slice

考虑以下代码(摘自RP Suri的 Prolog简介):

/* A set of father-child pairs declared */
father("Motilal", "Jawaharlal").
father("Motilal", "Vijayalakshmi").
father("Motilal", "Krishna").
father("Jawaharlal", "Indira").
father("Ranjit", "Tara").
father("Ranjit", "Lekha").
father("Ranjit", "Rita").
father("Feroz", "Sanjay").
father("Feroz", "Rajiv").
father("Sanjay", "Varun").
father("Rajiv", "Rahul").
father("Rajiv", "Priyanka").

/* Mothers declared */
wife_of("Swaruprani", "Motilal").
wife_of("Kamla", "Jawaharlal").
wife_of("Vijayalakshmi", "Ranjit").
wife_of("Indira", "Feroz").
wife_of("Maneka", "Sanjay").
wife_of("Sonia", "Rajiv").
wife_of("Priyanka", "Robert").

/* Predicates declared */
mother(M, C) :- wife_of(M, Hus) , father(Hus, C).

parent(P, C) :- mother(P, C) ; father(P, C).

ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- ancestor(X, Z) , parent(Z, Y).

现在,如果我查询

ancestor("Motilal", X)

我输出为:

?- ancestor("Motilal", X).
X = "Jawaharlal" ;
X = "Vijayalakshmi" ;
.
.
.
X = "Priyanka" ;

(这是正确的输出),之后程序停止,几秒钟后我收到消息:

ERROR: Out of local stack

当我查询

时会发生类似的事情
ancestor(X, "Motilal").

这应该什么也不返回,但是提示再次消失几秒钟,然后是相同的错误消息。代码中有什么问题?

1 个答案:

答案 0 :(得分:2)

要了解代码中的问题,无需查看整个程序。相反,它只需要看一小部分负责非终止:

?- ancestor(X, 'Motilal'), false.

ancestor(X, Y) :- false, parent(X, Y).
ancestor(X, Y) :- ancestor(X, Z) , false, parent(Z, Y).

此片段已经终止,因此整个程序不会终止。不管你在其他部分写的是什么!所以你需要在剩下的部分改变一些东西。否则,错误将持续存在。

有关详情,请参阅

你看到你需要改变什么吗?

  

将目标parent(Z, Y)放在前面!

顺便说一下,Prolog在这种情况下使用单引号原子很常见,因为这样效率更高!