您的位置:首页 > 其它

SICP 习题 (1.32)解题总结

2014-04-08 00:09 363 查看
SICP 习题1.32要求我们考察之前完成的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))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: