;accumulate递归版本 (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)))) ;sum测试,计算立方和 (define (cube-sum a b) (accumulate + 0 cube a next b)) ;product测试,计算阶乘 (define (factorial n) (define (f x) x) (accumulate * 1 f 1 next n))
(cube-sum 1 10)
(factorial 6)
结果
b)
1 2 3 4 5 6 7
;accumulate迭代版本 (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))
EX 1.33
a)
1 2 3 4 5 6 7 8 9 10 11 12
;相比EX 1.32,增加参数filter,用于过滤一些项 (define (filtered-accumulate combiner null-value filter f a next b) (if (> a b) null-value (if (filter a) (combiner (f a) (filtered-accumulate combiner null-value filter f (next a) next b)) (filtered-accumulate combiner null-value filter f (next a) next b)))) ;计算a到b之间素数和 (define (prime-sum a b) (define (f x) x) (filtered-accumulate + 0 prime? f a next b)) ;prime?见书P33页
其实可以使用let来定义剩余项,因为按照书中课后习题的学习顺序,这里并没有使用let
(let rest (filtered-accumulate combiner null-value filter f (next a) next b))
b)
1 2 3 4
(define (gcd-product n) (define (f x) x) (define (its-prime? x) (= (gcd x n) 1)) (filtered-accumulate * 1 its-prime? f 1 next n))