花了三週左右時間讀完了 "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. 若是想對遞歸/尾遞歸有更深刻的瞭解,這篇文章絕對值得一看~