Created
December 23, 2010 23:19
-
-
Save ashmoran/753674 to your computer and use it in GitHub Desktop.
SICP exercise 1.11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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) |
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
Could you replace lines 2-4 with (cond ((< n 4) n)
?