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 閱讀(217) 評論(0)  編輯  收藏 所屬分類: 個人學習日記sicp
          主站蜘蛛池模板: 泸西县| 临海市| 乐平市| 临沂市| 新建县| 江安县| 保定市| 镇坪县| 瑞金市| 定陶县| 高唐县| 张家界市| 黑水县| 尖扎县| 兴义市| 秭归县| 淮北市| 松溪县| 绥中县| 和田县| 周口市| 田阳县| 密山市| 海原县| 琼海市| 枞阳县| 泽库县| 长兴县| 碌曲县| 招远市| 开江县| 临洮县| 上饶市| 桂阳县| 泾川县| 马公市| 岫岩| 保亭| 邢台县| 磴口县| 宁武县|