From 5d17aa365558799a19729fec2b8acc8b7bcd3394 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Thu, 14 Mar 2019 13:40:04 -0400 Subject: [PATCH] Add some initial scheme code --- lib.scm | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 lib.scm diff --git a/lib.scm b/lib.scm new file mode 100644 index 0000000..6fa939b --- /dev/null +++ b/lib.scm @@ -0,0 +1,76 @@ +(define (sqrt x) + (define (average x y) (/ (+ x y) 2)) + (define (square x) (* x x)) + (define (good-enough? guess) + (< (abs (- (square guess) x)) 0.00001)) + (define (improve guess) + (average guess (/ x guess))) + (define (sqrt-iter guess) + (if (good-enough? guess) + guess + (sqrt-iter (improve guess)))) + (sqrt-iter 1.0)) + +;(define (factorial n) +; (if (= n 1) 1 (* n (factorial (- n 1))))) + +(define (factorial n) + (define (fact-iter product counter max-count) + (if (> counter max-count) + product + (fact-iter (* counter product) + (+ counter 1) + max-count))) + + (fact-iter 1 1 n)) + + +(define (A x y) + (cond ((= y 0) 0) + ((= x 0) (* 2 y)) + ((= y 1) 2) + (else (A (- x 1) + (A x (- y 1)))))) + +;(define (fib n) +; (cond ((= n 0) 0) +; ((= n 1) 1) +; (else (+ (fib(- n 1)) +; (fib(- n 2)))))) + +(define (fib n) + (define (fib-iter a b count) + (if (= count 0) + b + (fib-iter (+ a b) a (- count 1)))) + + (fib-iter 1 0 n)) + + +(define (count-change amount) + (define (first-denomination kinds-of-coins) + (cond ((= kinds-of-coins 1) 1) + ((= kinds-of-coins 2) 5) + ((= kinds-of-coins 3) 10) + ((= kinds-of-coins 4) 25) + ((= kinds-of-coins 5) 50))) + + (define (cc amount kinds-of-coins) + (cond ((= amount 0) 1) + ((or (< amount 0) + (= kinds-of-coins 0)) + 0) + (else + (+ (cc amount (- kinds-of-coins 1)) + (cc (- amount (first-denomination kinds-of-coins)) + kinds-of-coins))))) + + (cc amount 5)) + + +(define (ptri n) + (if (< n 3) n + (+ + (ptri (- n 1)) + (+ (* (ptri (- n 2)) 2) + (* (ptri (- n 3)) 3)))))