SICP 全笔记

Exercise 1.11. A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.

递归过程非常容易写出来。只需要根据函数定义就可以。

(define (f/rec n)
  (cond ((< n 3) n)
        (else
         (+ (f/rec (- n 1))
            (* 2 (f/rec (- n 2)))
            (* 3 (f/rec (- n 3)))))))

对于迭代的版本,我们必须知道,迭代的过程在每次迭代中都保存了当前的结果,它不可能像递归那样去为了得到 fn 的值才去计算 fn-1 的值,所以迭代总是从 n 可以取的某一个边界值开始,一直迭代到 n 的另外一个边界值。

(define (f/iter n)
  (define (iter fn-1 fn-2 fn-3 counter)
    (cond ((< n 3) n)
          ((> counter n) fn-1)
          (else
           (iter (+ fn-1 (* 2 fn-2) (* 3 fn-3))
                 fn-1 fn-2
                 (+ counter 1)))))
  (iter 2 1 0 3))

;;; tests begin
(load "../testframe.scm")

(for-each (lambda (x)
            (assert= (f/rec x) (f/iter x)))
          '(1 2 3 4 5 6 7 8 9 10))