无法理解为什么 prolog 无限循环 [英] Can't understand why is prolog looping infinitly

查看:76
本文介绍了无法理解为什么 prolog 无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘自 Bratko 的书,面向人工智能的 Prolog 编程(第 4版)我们有以下不起作用的代码 -

From Bratko's book, Prolog Programming for Artificial Intelligence (4th Edition) We have the following code which doesn't work -

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

在本书第 55 页的图 2.15 中,显示 parent(Y,Z) 一直在调用,直到堆栈内存不足.

In the book, on page 55, figure 2.15, is shown that parent(Y,Z) is kept calling until stack is out of memory.

我不明白的是 prolog 对 anc4(X,Y) 进行递归调用,而不是先对父 (Y,Z) 进行递归调用.为什么 prolog 不一遍又一遍地转到第一行anc4(X,Y),而是转到第二行?

What I don't understand is that prolog does a recursiv call to anc4(X,Y), and not to parent (Y,Z) first. Why doesn't prolog goes over and over to the first line, anc4(X,Y), and rather goes to the second line?

你能详细说明为什么行 parent(Y,Z) 一直被调用吗?

Can you please elaborate why is the line parent(Y,Z) is kept being called?

谢谢.

推荐答案

问题"(即目标顺序)的根源深深植根于语言的基础.

The origin of your 'problem' (i.e. goals order) is deeply rooted in the basic of the language.

Prolog 基于时间顺序回溯的简单高效策略,实现 SLD 解析和左递归子句,如 anc4/2,导致无限递归.事实上,逗号运算符 (,)/2 代表

Prolog is based on the simple and efficient strategy of chronological backtracking, to implement SLD resolution, and left recursive clauses, like anc4/2, cause an infinite recursion. Indeed, the comma operator (,)/2 stands for

如果左表达式成立,则评估右表达式

evaluate the right expression only if the left expression holds

因此,子句中的目标顺序实际上是程序的重要组成部分.

So, order of goals in a clause is actually an essential part of the program.

对于您的具体案例,

... , parent(Y,Z).

如果

anc4(X,Y), 

不成立.

目标顺序对应的是子句顺序.

即子句交换后整个程序的语义不同:

That is, the whole program has a different semantics after the clauses are exchanged:

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

为了更好地理解这个问题,我认为也值得尝试一下这个定义.

To better understand the problem, I think it's worth to try this definition as well.

这篇关于无法理解为什么 prolog 无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆