Question

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?

Was it helpful?

Solution

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.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top