Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Created December 23, 2010 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashmoran/753674 to your computer and use it in GitHub Desktop.
Save ashmoran/753674 to your computer and use it in GitHub Desktop.
SICP exercise 1.11
(define (f n)
(cond ((= n 1) 1)
((= n 2) 2)
((= n 3) 3)
(else (+ (f (- n 1))
(* 2 (f (- n 2)))
(* 3 (f (- n 3))))))
)
(define (g n)
(define (iter a b c count max)
(if (> count max)
c
(iter b c (+ (* 3 a) (* 2 b) c) (+ count 1) max))
)
(cond ((= n 1) 1)
((= n 2) 2)
((iter 1 2 3 4 n)))
)
(define (expect actual expectation expected)
(assert (= actual expected))
(display ".")
)
(define to-equal 1)
(expect (f 1) to-equal 1)
(expect (f 2) to-equal 2)
(expect (f 3) to-equal 3)
(expect (f 4) to-equal 10)
(expect (f 5) to-equal 22)
(expect (g 1) to-equal 1)
(expect (g 2) to-equal 2)
(expect (g 3) to-equal 3)
(expect (g 4) to-equal 10)
(expect (g 5) to-equal 22)
@bishboria
Copy link

Could you replace lines 2-4 with (cond ((< n 4) n)

?

@ashmoran
Copy link
Author

ashmoran commented Jan 5, 2011

Yes :-)

I realised this code was not the best but once I'd finally got it working, I wasn't in the mood to fix it. Future exercise solutions are getting better...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment