1.29
(define (simpson f a b n)
(define (get-h) (/ (- b a) n))
(define (get-y k) (f (+ a (* k (get-h)))))
(define (simpson-term k)
(cond ((= k 0) (get-y k))
((= k n) (get-y k))
((= (remainder k 2) 0) (* 2.0 (get-y k)))
(else (* 4.0 (get-y k)))))
(define (simpson-next k) (+ k 1))
(* (/ (get-h) 3.0) (sum simpson-term 0 simpson-next n)))
1.30
(define (sum term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (+ (term a) result))))
(iter a 0))
1.31
;;递归
(define (product-re term a next b)
(if (> a b)
1
(* (term a)
(product-re term (next a) next b))))
;;迭代
(define (product term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (* result (term a)))))
(iter a 1))
(define (pi-product b)
(define (pi-term k) (/ (* (- k 1) (+ k 1)) k k))
(define (pi-next k) (+ k 2))
;;(* 4.0 (product-re pi-term 3.0 pi-next b))) ;;递归
(* 4.0 (product pi-term 3.0 pi-next b))) ;;迭代
1.32
(define (sum term a next b)
(accumulate + 0 term a next b))
(define (product term a next b)
(accumulate * 1 term a next b))
;;递归
(define (accumulate-re combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a)
(accumulate-re combiner null-value term (next a) next b))))
;;迭代
(define (accumulate combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner (term a) result))))
(iter a null-value))
1.33
(define (filtered-accumulate combiner null-value term a next b filter?)
(define (iter a result)
(if (> a b)
result
(if (filter? (term a))
(iter (next a) (combiner (term a) result))
(iter (next a) result))))
(iter a null-value))
(define (sum-prime a b)
(define (sum-prime-term k) k)
(define (sum-prime-next k) (+ k 1))
(filtered-accumulate + 0 sum-prime-term a sum-prime-next b prime?))
(define (relatively-prime-product n)
(define (relatively-prime? k) (= (gcd k n) 1))
(define (term k) k)
(define (next k) (+ k 1))
(filtered-accumulate * 1 term 2 next (- n 1) relatively-prime?))