Exercise 3.1. An accumulator is a procedure that is called repeatedly with a single numeric argument and accumulates its arguments into a sum. Each time it is called, it returns the currently accumulated sum. Write a procedure make-accumulator that generates accumulators, each maintaining an independent sum. The input to make-accumulator should specify the initial value of the sum; for example
(define A (make-accumulator 5))
(A 10)
15
(A 10)
25
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (define (make-accumulator sum) | |
| (define (accumulate add-to-sum) | |
| (set! sum (+ sum add-to-sum)) | |
| sum) | |
| (define (dispatch m) | |
| (cond ((eq? m 'accumulate) accumulate) | |
| (else (error "Unknown request — MAKE-ACCOUNT" | |
| m)))) | |
| (dispatch 'accumulate)) | |
| (define A (make-accumulator 100)) | |
| (A 50) | |
| (A 5) | |
| (A 150) | |