sicp/lib.scm
2019-03-15 15:15:07 -04:00

128 lines
2.8 KiB
Scheme

#lang sicp
(define (average x y) (/ (+ x y) 2))
(define (square x) (* x x))
(define (cube x) (* x x x))
(define (% a b)
(remainder a b))
(define (sqrt 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)))))
(define (p x) (- (* 3 x) (* 4 (cube x))))
(define (sine angle)
(if (not (> (abs angle) 0.1))
angle
(p (sine (/ angle 3.0)))))
;(define (expt b n)
; (if (= n 0) 1 (* b (expt b (- n 1)))))
(define (expt b n) (expt-iter b n 1))
(define (expt-iter b counter product)
(if (= counter 0)
product
(expt-iter b
(- counter 1)
(* b product))))
(define (fast-exp b n)
(cond ((= n 0)
1)
((even? n)
(square (fast-exp b (/ n 2))))
(else
(* b (fast-exp b (- n 1))))))
(define (gcd a b)
(if (= b 0)
a
(gcd b (% a b))))
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n)
n)
((divides? test-divisor n)
test-divisor)
(else (find-divisor
n
(+ test-divisor 1)))))
(define (divides? a b)
(= (% b a) 0))
(define (prime? n)
(= n (smallest-divisor n)))