sicp/lib.scm

77 lines
1.8 KiB
Scheme
Raw Normal View History

2019-03-14 13:40:04 -04:00
(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)))))