明日(2008/03/24)の勉強会に備えて、少し過去の問題を解いています。
問題文。
Exercise 1.11. A function f is defined by the rule that f(n) = n 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 n) (cond ((< n 3) n) (else (+ (f (- n 1)) (* 2 (f (- n 2))) (* 3 (f (- n 3)))) ) ))(print (f 2))(print (f 3))(print (f 4))(print (f 5))(print (f 10))
反復的に実現するコード。
(define (f-iter n) (define (iter a b c count) (cond ((= count 0) c) ((= count 1) b) (else (iter (+ a (* 2 b) (* 3 c)) a b (- count 1))))) (iter 2 1 0 n))(print (f-iter 2))(print (f-iter 3))(print (f-iter 4))(print (f-iter 5))(print (f-iter 10))

コメント一覧
この記事にコメントしてください
(*) は必須入力項目です。