3

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?

4

1 に答える 1

5

のこれら 2 つの使用法はaccumulate、「要素をコンシングしてリストを作成する」ことは、「積を得るために数を掛ける」または「数を合計して得る」のと同じように、累積プロセスとして扱うことができるという事実を単に示しているに過ぎないと確信しています。合計」ができます。蓄積が事実上ノーオペレーションであることは間違いありません。

filter(余談: の出力と入力がaccumulateリストでない場合、たとえば、遅延生成されたシーケンスを表す場合、これは明らかにより便利な操作になる可能性があることに注意してください。)

于 2010-09-08T21:55:16.723 に答える