sicp-ex-3.1



<< Previous exercise (2.97) | Index | Next exercise (3.2) >>


The solution here presents itself: use lexical closure.

 (define (make-accumulator initial-value) 
   (let ((sum initial-value)) 
     (lambda (n) 
       (set! sum (+ sum n)) 
       sum))) 

pluies

Lexical closure is indeed the way to go.

You can also use the trick that the initial value passed as parameter is already part of the lexical scope to save an instruction and write the accumulator as:

 (define (make-accumulator acc) 
   (lambda (x) 
     (set! acc (+ x acc)) 
     acc)) 

Rather Iffy

I prefer 'sum' for the result of accumulation. Acc could be confused with the accumulator object itself.

 (define (make-accumulator sum) 
   (lambda (x) 
     (set! sum (+ x sum)) 
     sum))