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.

          recursive:

          (define (fn n)
            (cond ((>= n 3) (+ (+ (fn (- n 1)) (* 2 (fn (- n 2)))) (* 3 (fn (- n 3)))))
                  ((< n 3) n)
             ))


           iterative:

          (define (re n)
            (if (< n 3)
                n
                (iter 2 1 0 n)
                ))
          (define (iter a b c n)
          (if(= n 3)
             (ca a b c)
             (iter (ca a b c) a b (- n 1))
             )
          )
          (define (ca a b c)
            (+ a (* 2 b) (* 3 c) )
          )

          posted on 2009-03-10 08:51 lzj520 閱讀(213) 評論(0)  編輯  收藏 所屬分類: 個人學(xué)習(xí)日記sicp
          主站蜘蛛池模板: 昭通市| 建昌县| 枞阳县| 河东区| 盈江县| 沾益县| 股票| 涞源县| 卢湾区| 克什克腾旗| 龙南县| 许昌市| 临湘市| 恩平市| 博罗县| 大庆市| 班戈县| 鹰潭市| 横山县| 上栗县| 大关县| 司法| 阳朔县| 澄城县| 东辽县| 鹤山市| 宝兴县| 平乡县| 固始县| 资阳市| 且末县| 靖边县| 青海省| 宁武县| 三门峡市| 九江县| 松原市| 玉田县| 阳原县| 疏附县| 沁阳市|