lambdaphant’s posterous

lambdaphant’s posterous

Michael Matuzak  //  Programmer by day, booze drinking calamari cruncher by night.

Jan 7 / 8:49pm

SICP Exercise 1.11

Recursive:
 
(define (rf n)
  (if (< n 3)
  n
  (+ (rf (- n 1))
   (* 2 (rf (- n 2)))
   (* 3 (rf (- n 3))))))
 
Iterative:
 
(define (f n)
  (if (< n 3)
  n
  (f-iter 0 1 2 n)))
 
(define (f-iter a b c counter)
  (if (= 0 counter)
  a
  (f-iter b c (+ c (* 2 b) (* 3 a)) (- counter 1))))

 
The iterative one took me a while to figure out. Every time I started I kept reverting back to recursive thinking.

Loading mentions Retweet

0 comments

Leave a comment...

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    Connect    twitter