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

查看:122
本文介绍了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中是重要的(阅读 basic )主题,因为它允许逆向传递一些基本算法,对程序的效率具有重要意义。

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(天真相反),它是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天全站免登陆