SICP 习题 (1.32)解题总结
2014-04-08 00:09
363 查看
SICP 习题1.32要求我们考察之前完成的sum过程和product 过程,说明它们是名为accumulate的过程的特殊情况。
反过来说的话,就是要我们对sum过程和product过程进行抽象,形成一个更普遍,更通用的过程。
我们在习题1.31的解题总结中已经讨论了,其实sum过程和product过程相差很小,就是累积的操作不一样,初始化的数值不一样。
这样,我们就可以将不同的东西抽离出来,定义一个更广泛的过程,按题目要求,把这个过程叫做accumulate过程,accumulate就是“累积”的意思。
我定义的accumulate过程如下:
可以看出,它和sum过程或者是product过程很像,就是加了combiner参数和null-value参数,用combiner参数代替+号和*号,用null-value代替0和1。
如果用accumulate来实现sum的话是这样的:
实现的product应该是这个样子的:
然后,题目要求我们实现迭代版的accumulate,这个对我们来讲就不算太难了,过程如下:
反过来说的话,就是要我们对sum过程和product过程进行抽象,形成一个更普遍,更通用的过程。
我们在习题1.31的解题总结中已经讨论了,其实sum过程和product过程相差很小,就是累积的操作不一样,初始化的数值不一样。
这样,我们就可以将不同的东西抽离出来,定义一个更广泛的过程,按题目要求,把这个过程叫做accumulate过程,accumulate就是“累积”的意思。
我定义的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过程或者是product过程很像,就是加了combiner参数和null-value参数,用combiner参数代替+号和*号,用null-value代替0和1。
如果用accumulate来实现sum的话是这样的:
(define (sum term a next b) (accumulate + 0 term a next b))
实现的product应该是这个样子的:
(define (product term a next b) (accumulate * 1 term a next b))
然后,题目要求我们实现迭代版的accumulate,这个对我们来讲就不算太难了,过程如下:
(define (accumulate-iter 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))
相关文章推荐
- SICP 习题 (1.36)解题总结
- SICP 习题 (2.2) 解题总结:用复合数据表示点和线段
- SICP 习题 (1.35)解题总结
- SICP 习题 (2.28)解题总结:树状列表的遍历
- SICP 习题 (2.31)解题总结 : 通用的Square-Tree
- SICP 习题 (1.34)解题总结
- SICP 习题 (1.7) 解题总结
- SICP 习题 (2.29) 解题总结:二叉活动体
- SICP 习题(1.1,1.2,1.3,1.4)解题总结。
- SICP 习题 (2.16)解题总结:避免误差的区间计算系统
- SICP 习题 (1.14)解题总结
- SICP 习题 (1.16)解题总结
- SICP 习题 (1.31)解题总结
- SICP 习题 (1.8) 解题总结
- SICP 习题 (2.30)解题总结 : Square-Tree
- SICP 习题 (2.1) 解题总结:用复合数据表示有理数
- SICP 习题 (1.14)解题总结
- SICP 习题 (1.16)解题总结
- SICP 习题 (2.7) 解题总结 : 定义区间数据结构
- SICP 习题 (1.20) 解题总结