tags:

views:

62

answers:

1

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?

+3  A: 

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

mquander
It also seems to be intentionally trying to copy the structure of even-fibs here: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html#%_idx_1724 to illustrate the parallels.
Tim Snowhite
It's also important to note that if you continue in scheme, a standard library foldr might be able to handle different forms of sequences beyond lists, and if you want the result to be a list, then cons-ing might be appropriate. (That's the only other case I can think of that you might want to do this sort of thing.)
Tim Snowhite
Ah, that makes sense, both that non-list sequences may be used, and that this is demonstrating a kind of mechanical transformation of the earlier even-fibs function. Thank you both, this has been bugging me since I read it earlier this week.
Jared