博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【SICP练习】26 练习1.32
阅读量:4686 次
发布时间:2019-06-09

本文共 1333 字,大约阅读时间需要 4 分钟。



练习1.32

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

(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个地方的区别。按照题中的要去,我们将01的位置用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))))

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

(define (sum term a next b)

   (accumulate + 0 term a next b))

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

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

通过这些对比,感觉枯燥的递归和迭代还挺有意思的。

版权声明:本文为 NoMasp柯于旺 原创文章,如需转载请联系本人。

转载于:https://www.cnblogs.com/NoMasp/p/4786204.html

你可能感兴趣的文章
失去光标display=none事件的坑
查看>>
Python3.x:函数定义
查看>>
NOI 2014 起床困难综合症
查看>>
[LeetCode] Majority Element II
查看>>
设计模式的理解
查看>>
[cocos2dx动作]CCLabel类数字变化动作
查看>>
(转)Excel的 OleDb 连接串的格式(连接Excel 2003-2013)
查看>>
JAVA面试——分布式锁
查看>>
HDU2588--GCD(欧拉函数)
查看>>
负载均衡服务器
查看>>
ruby之gem install
查看>>
Linux下samba编译与安装(Ubuntu和嵌入式linux)
查看>>
jquery 获取后台实时数据
查看>>
BZOJ 3239 Discrete Logging(BSGS)
查看>>
Oracle 触发器实现主键自增
查看>>
vmware中三种网络连接方式(复制)
查看>>
Java并发编程
查看>>
[转]MySQL数据库管理常用命令
查看>>
Git Stash用法
查看>>
线程与同步
查看>>