SICP 全笔记

Exercise 1.30. The sum procedure above generates a linear recursion. The procedure can be rewritten so that the sum is performed iteratively. Show how to do this by filling in the missing expressions in the following definition:

(define (sum term a next b)
  (define (iter a result)
    (if <??>
        <??>
        (iter <??> <??>)))
  (iter <??> <??>))

迭代式的 sum 可以如下写:

(define (sum term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a)
              (+ (term a) result))))
  (iter a 0))

同样,我们需要进行测试

(load "../testframe.scm")

; cube
(define (inc n) (+ n 1))
(define (sum-cubes a b)
  (sum cube a inc b))
(assert= (sum-cubes 1 10) 3025)

; sum-integers
(define (identity x) x)
(define (sum-integers a b)
  (sum identity a inc b))
(assert= (sum-integers 1 10) 55)