花了三周左右时间读完了 "Structure and Interpretation of Computer Programs" 第一章,完成了大部分的习题,在这里记录下书中的一些精华段落,以及我的的一些感悟。git
首先,截取一段书中对于“迭代和递归”的描述:程序员
The contrast between the two processes can be seen in another way. In the iterative case, the program variables provide a complete description of the state of the process at any point. If we stopped the computation between steps, all we would need to do to resume the computation is to supply the interpreter with the values of the three program variables. Not so with the recursive process. In this case there is some additional “hidden” information, maintained by the interpreter and not contained in the program variables, which indicates “where the process is” in negotiating the chain of deferred operations. The longer the chain, the more information must be maintained.
这段描述再配合上计算 factorial 的过程(process),把迭代和递归的区别清晰地展现了出来。github
递归从“形状”上看,先增大再缩小;而迭代倒是线性的。这里所谓的“形状”就是计算所须要的空间。
另外,递归还须要把一部分“隐藏状态”交给 interpreter 来维护;而迭代倒是把全部的状态放在参数里。这样致使的结果就是,若是计算过程当中断,迭代能够从中断的地方开始继续执行,而递归则不行,由于那部分隐藏的状态已经丢失了。编程
再截取书中的一段注解#30:less
When we discuss the implementation of procedures on register machines in chapter 5, we will see that any iterative process can be realized “in hardware” as a machine that has a fixed set of registers and no auxiliary memory. In contrast, realizing a recursive process requires a machine that uses an auxiliary data structure known as a stack.
固然,递归也有优势,递归能让咱们更好的理解问题,并且在处理一些有层次关系的数据时,用递归更天然。编程语言
One should not conclude from this that tree-recursive processes are useless. When we consider processes that operate on hierarchically structured data rather than numbers, we will find that tree recursion is a natural and powerful tool.32 But even in numerical operations, tree-recursive processes can be useful in helping us to understand and design programs.
此外,书中把 Process 和 Procedure 的对比描述地也很精彩。简单来讲,Process 属于概念上的东西,跟具体语言无关,而 Procedure 是用具体的编程语言把 Process 实现出来。ide
迭代过程(iterative process)也能够用递归程序(recursive procedure)来实现,由于 Scheme 之类的语言实现支持“尾递归”(tail-recursive),所以常见的 for,while 之类的循环原语只是做为语法糖(syntatic sugar)而存在。而其余没有支持尾递归的语言(C, Python)则须要借助 for,while 来实现迭代过程。ui
读完第一章后,不得不佩服本书的两位做者,平淡的几句话就能把不少深入的问题解释地很是透彻,可能这也就是为何这本书在老派的程序员当中至关受推崇。this
接下来几天(也许几周?)准备写下第一章的重点:使用程序(procedure)来构建抽象,从而使得复杂的逻辑更简单易懂,也更灵活易改。spa
P.S. 若是想对递归/尾递归有更深刻的了解,这篇文章绝对值得一看~