乐正

Actions speak louder than words.

Sicp-ex3-1

问题

一个累加器是一个过程,反复用数值参数调用它,就会是它的各个参数累加到一个和数中。每次调用时,累加器将返回当前的累加和。请写出一个生成累加器的过程make-accumulator,它所生成的每个累加器维持着一个独立的和。松给make-accumulate的输入描述了有关和的初始值,例如:

1
2
3
4
5
6
7
(define A (make-accumulator 5))

(A 10)
15

(A 10)
25

解答

1
2
3
4
(define (make-accumulator v)
  (lambda (value)
    (set! v (+ value v))
    v))

测试

1
2
3
4
5
6
7
8
(define a (make-accumulator 10))
;Value: a

(a 1)
;Value: 11

(a 10)
;Value: 21

draft

« sicp-ex2-91 sicp-ex3-2 »

Comments