【SICP练习】26 练习1.32



练习1.32

因为递归比迭代要更容易实现,因此我先考虑的递归。先将sum和product都列出来。

(define (sum term a next b)

       (if(> a b)

      0

      (+(term a)

        (sum term (next a) next b))))

(define (product term a next b)

    (if(> a b)

       1

      (* (term a)

        (product term (next a) next b))))

通过对比我们发现,仅仅是有2个地方的区别。按照题中的要去,我们将0或1的位置用null-value代替,将+或*用combiner代替。在函数的参数中添加这两个新的参数即可。通过对比,其实也不难嘛。

(define (accumulate combinernull-value term a next b)

    (if (> a b)

       null-value

       (combiner (term a) (accumulate combinernull-value term (next a) next b))))

题中还要求我们定义出sum和product来,这里我就列出sum的递归accumulate版本。

(define (sum term a next b)

   (accumulate + 0 term a next b))

接下来我们再看看如何写出迭代版本的accumulate。还是一样,先列出迭代版本的sum和product。

(define (sum term a next b)

   (define (sum-iter a other)

       (if (> a b)

         other

          (sum-iter (next a)

(+(term a) other))))

   (sum-iter a 0))

(define (product term a next b)

   (define (product-iter a other)

       (if (> a b)

          other

          (product-iter (next a)

                        (* (term a) other))))

   (product-iter a 1))

同样是通过类比,我们又可以写出迭代版本的accumulate。

(define (accumulate combinernull-value term a next b)

    (define (accumulate-iter a other)

       (if (> a b)

          other

          (accumulate-iter (next a)

                          (combiner (term a)other))))

   (accumulate-iter a null-value))

这次我们就来写迭代版本的product。

(define (product term a nextb)

        (accumulate * 1 term a next b))

通过这些对比,感觉枯燥的递归和迭代还挺有意思的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值