SICP 习题 (1.32)解题总结

88 篇文章 30 订阅
74 篇文章 0 订阅

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))



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值