1.32

练习 1.32

a) 请说明,sum和product(练习1.31)都是另一称为accumulate的更一般概念的特殊情况,accumulate使用某些一般性的累积函数组合起一系列项:

(accumulate combiner null-value term a next b)

accumulate取的是与sum和product一样的项和范围描述参数,再加上一个(两个参数的)combiner过程,它描述如何将当前项与前面各项的积累结果组合起来,另外还有一个null-value参数,它描述在所有的项都用完时的基本值。请写出accumulate,并说明我们能怎样基于简单地调用accumulate,定义出sum和product来。

b) 如果你的accumulate过程生成的是一个递归计算过程,那么请写出一个生成迭代计算过程的过程。如果它生成一个迭代计算过程,那么请写出一个生成递归计算过程的过程。

a) 递归实现:

(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 + 0 term a next b)) (define (product term a next b) (accumulate * 1 term a next b)) (define (cube x) (* x x x)) (define (inc x) (+ x 1)) (sum cube 1 inc 10) (define (identity x) x) (product identity 1 inc 10)

b) 迭代实现:

(define (accumulate combiner null-value term a next b) (define (iter a result) (if (> a b) result (iter (next a) (combiner result (term a ))))) (iter a null-value)) (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 (cube x) (* x x x)) (define (inc x) (+ x 1)) (sum cube 1 inc 10) (define (identity x) x) (product identity 1 inc 10)

results matching ""

    No results matching ""