SICP累积功能

发布于 2024-09-18 04:00:56 字数 907 浏览 2 评论 0原文

计算机程序的结构和解释 (SICP) 第 2.2.3 节 定义了几个函数:

(accumulate cons nil 
  (filter pred
         (map op sequence)))

使用此函数对斐波那契数列表进行操作的两个示例,even-fibslist-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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

世界等同你 2024-09-25 04:00:56

我确信 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 of accumulate was not a list; for example, if it represented a lazily generated sequence.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文