Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SICP Accumulate function

Tags:

scheme

sicp

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?

like image 751
Jared Avatar asked Nov 20 '25 21:11

Jared


1 Answers

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

like image 184
mqp Avatar answered Nov 24 '25 08:11

mqp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!