2009年1月2日星期五

sicp习题解答sec_1.3.1

上一节

;;Exercise 1.29
(define (Simpson f a b n)
(define h (/ (- b a) n)) ; n is an even number

(define (y k)
(f (+ a (* k h))))

(define (iter i)
(if (< i n)
(if (even? i)
(+ (* 2 (y i))
(iter (+ i 1)))
(+ (* 4 (y i))
(iter (+ i 1))))
0))

(* (/ h 3)
(+ (y 0)
(y n)
(iter 1))))


(define (cube x)
(* x x x))

(Simpson cube 0 1 100)
(Simpson cube 0 1 1000)


;;Exercise 1.30
(define (sum term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (+ result (term a)))))
(iter a 0))


;;Exercise 1.31
;a)
(define (product term a next b)
(if (> a b)
1
(* (term a)
(product term (next a) next b))))

(define (factorial n)
(define (identity x) x)
(define (inc x) (+ x 1))
(product identity 1 inc n))

(define (pi n)
(* 4 (product (lambda (x) (/ (* (- x 1.0) (+ x 1)) (* x x)))
3
(lambda (x) (+ x 2))
n)))

(pi 1000000)


;b)
(define (product2 term a next b)
(define (iter prod i)
(if (> i b)
prod
(iter (* (term i) prod) (next i))))
(iter 1 a))


;;Exercise 1.32
(define (accumulate combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a) (accumulate combiner null-value term (next a) next b))))

(define (sum term a next b)
(accumulate (lambda (x y) (+ x y)) 0 term a next b))

(define (product term a next b)
(accumulate (lambda (x y) (* x y)) 1 term a next b))


;b)
(define (accumulate2 combiner null-value term a next b)
(define (iter result i)
(if (> i b)
result
(iter (combiner result (term i)) (next i))))
(iter null-value a))



;;Exercise 1.33
(define (filtered-accumulate combiner null-value term a next b filter)
(define (iter result i)
(if (> i b)
result
(iter (combiner result
(if (filter i)
(term i)
null-value))
(next i))))
(iter null-value a))


;a) #中文版题目没平方.
(define (sum-of-squares-of-primes a b)
(filtered-accumulate (lambda (x y) (+ x y))
0
square
a
inc
b
prime?))

;b)
(define (relatively-prime-to-n? i)
(= 1 (gcd i n)))

(define (profuct-of-relaviely-prime-to-n n)
(filtered-accumulate (lambda (x y) (* x y))
1
identity
1
inc
(- n 1)
relatively-prime-to-n?))



没有评论: