SICP累积功能
计算机程序的结构和解释 (SICP) 第 2.2.3 节 定义了几个函数:
(accumulate cons nil
(filter pred
(map op sequence)))
使用此函数对斐波那契数列表进行操作的两个示例,even-fibs
和list-fib-squares
。
Accumulate、Filter 和 Map 函数也在 2.2 节中定义。让我困惑的是为什么作者在这里包含了accumulate。 accumulate
需要 3 个参数:
要应用的二元函数
初始值,用作函数最右边的参数
将应用函数的列表
中的定义将累加应用于列表的示例book:
(accumulate cons nil (list 1 2 3))
=> (cons 1 (cons 2 (cons 3 nil)))
=> (1 2 3)
由于第三个参数是一个列表,因此 (accumulate cons nil some-list)
将仅返回 some-list
,在本例中为 (过滤器pred(映射操作序列))
是一个列表。
除了与本节中其他类似结构的函数保持一致之外,使用 accumulate
是否还有其他原因?
In Structure and Interpretation of Computer Programs (SICP) Section 2.2.3 several functions are defined using:
(accumulate cons nil
(filter pred
(map op sequence)))
Two examples that make use of this operate on a list of the fibonacci numbers, even-fibs
and list-fib-squares
.
The accumulate, filter and map functions are defined in section 2.2 as well. The part that's confusing me is why the authors included the accumulate
here. accumulate
takes 3 parameters:
A binary function to be applied
An initial value, used as the rightmost parameter to the function
A list to which the function will be applied
An example of applying accumulate to a list using the definition in the book:
(accumulate cons nil (list 1 2 3))
=> (cons 1 (cons 2 (cons 3 nil)))
=> (1 2 3)
Since the third parameter is a list, (accumulate cons nil some-list)
will just return some-list
, and in this case the result of (filter pred (map op sequence))
is a list.
Is there a reason for this use of accumulate
other than consistency with other similarly structured functions in the section?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我确信
accumulate
的这两种用法只是说明了这样一个事实:“使用元素来构建列表”可以被视为一个累积过程,就像“将数字相乘以获得一个列表”一样。产品”或“将数字相加以获得总数”都可以。你是对的,积累实际上是一个空操作。(旁白:请注意,如果
filter
的输出和accumulate
的输入不是列表,这显然是一个更有用的操作;例如,如果它表示延迟生成的顺序。)I'm certain that those two uses of
accumulate
are merely illustrative of the fact that "consing elements to construct a list" can be treated as an accumulative process in the same way that "multiplying numbers to obtain a product" or "summing numbers to obtain a total" can. You're correct that the accumulation is effectively a no-op.(Aside: Note that this could obviously be a more useful operation if the output of
filter
and input ofaccumulate
was not a list; for example, if it represented a lazily generated sequence.)