Prolog 累加器.他们真的是“不同的"吗?概念? [英] Prolog Accumulators. Are they really a "different" concept?

查看:23
本文介绍了Prolog 累加器.他们真的是“不同的"吗?概念?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的人工智能实验室学习 Prolog,来源立即学习 Prolog!.

I am learning Prolog under my Artificial Intelligence Lab, from the source Learn Prolog Now!.

在第 5 章中,我们将学习累加器.作为示例,给出了这两个代码片段.查找列表的长度

In the 5th Chapter we come to learn about Accumulators. And as an example, these two code snippets are given. To Find the Length of a List

没有累加器:

len([],0).
len([_|T],N) :- len(T,X), N is X+1.

带累加器:

accLen([_|T],A,L) :- Anew is A+1, accLen(T,Anew,L).
accLen([],A,A).

我无法理解,这两个片段在概念上有何不同?累加器究竟有什么不同?有什么好处?

累加器听起来像中间变量.(如果我错了,请纠正我.)而且我已经在我的程序中使用过它们,所以它真的有那么大的概念吗?

Accumulators sound like intermediate variables. (Correct me if I am wrong.) And I had already used them in my programs up till now, so is it really that big a concept?

推荐答案

累加器中间变量,一个重要的(阅读基本) 主题在 Prolog 中,因为允许反转一些基本算法的信息流,对程序的效率有重要影响.

accumulators are intermediate variables, and are an important (read basic) topic in Prolog because allow reversing the information flow of some fundamental algorithm, with important consequences for the efficiency of the program.

以反转列表为例

nrev([],[]).
nrev([H|T], R) :- nrev(T, S), append(S, [H], R).

rev(L, R) :- rev(L, [], R).
rev([], R, R).
rev([H|T], C, R) :- rev(T, [H|C], R).

nrev/2 (naive reverse) 它是 O(N^2),其中 N 是列表长度,而 rev/2 它是 O(N).

nrev/2 (naive reverse) it's O(N^2), where N is list length, while rev/2 it's O(N).

这篇关于Prolog 累加器.他们真的是“不同的"吗?概念?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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