譯者按: 程序員應該知道遞歸,但是你真的知道是怎么回事么?
為了保證可讀性,本文采用意譯而非直譯。
遞歸簡介
一個過程或函數在其定義或說明中有直接或間接調用自身的一種方法,它通常把一個大型復雜的問題層層轉化為一個與原問題相似的規模較小的問題來求解,遞歸策略只需少量的程序就可描述出解題過程所需要的多次重復計算,大大地減少了程序的代碼量。
我們來舉個例子,我們可以用4的階乘乘以4來定義5的階乘,3的階乘乘以4來定義4的階乘,以此類推。
factorial(5) = factorial(4) * 5
factorial(5) = factorial(3) * 4 * 5
factorial(5) = factorial(2) * 3 * 4 * 5
factorial(5) = factorial(1) * 2 * 3 * 4 * 5
factorial(5) = factorial(0) * 1 * 2 * 3 * 4 * 5
factorial(5) = 1 * 1 * 2 * 3 * 4 * 5
用Haskell的Pattern matching 可以很直觀的定義factorial函數:
factorial n = factorial (n-1) * n
factorial 0 = 1
在遞歸的例子中,從第一個調用factorial(5)
開始,一直遞歸調用factorial
函數自身直到參數的值為0。下面是一個形象的圖例:

遞歸的調用棧
為了理解調用棧,我們回到factorial
函數的例子。
function factorial(n) {
if (n === 0) {
return 1
}
return n * factorial(n - 1)
}
如果我們傳入參數3,將會遞歸調用factorial(2)
、factorial(1)
和factorial(0)
,因此會額外再調用factorial
三次。
每次函數調用都會壓入調用棧,整個調用棧如下:
factorial(0) // 0的階乘為1
factorial(1) // 該調用依賴factorial(0)
factorial(2) // 該調用依賴factorial(1)
factorial(3) // 該掉用依賴factorial(2)
現在我們修改代碼,插入console.trace()
來查看每一次當前的調用棧的狀態:
function factorial(n) {
console.trace()
if (n === 0) {
return 1
}
return n * factorial(n - 1)
}
factorial(3)
接下來我們看看調用棧是怎樣的。
第一個:
Trace
at factorial (repl:2:9)
at repl:1:1 // 請忽略以下底層實現細節代碼
at realRunInThisContextScript (vm.js:22:35)
at sigintHandlersWrap (vm.js:98:12)
at ContextifyScript.Script.runInThisContext (vm.js:24:12)
at REPLServer.defaultEval (repl.js:313:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.onLine (repl.js:513:10)
at emitOne (events.js:101:20)
你會發現,該調用棧包含一個對factorial
函數的調用,這里是factorial(3)
。接下來就更加有趣了,我們來看第二次打印出來的調用棧:
Trace
at factorial (repl:2:9)
at factorial (repl:7:12)
at repl:1:1 // 請忽略以下底層實現細節代碼
at realRunInThisContextScript (vm.js:22:35)
at sigintHandlersWrap (vm.js:98:12)
at ContextifyScript.Script.runInThisContext (vm.js:24:12)
at REPLServer.defaultEval (repl.js:313:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.onLine (repl.js:513:10)
現在我們有兩個對factorial
函數的調用。
第三次:
Trace
at factorial (repl:2:9)
at factorial (repl:7:12)
at factorial (repl:7:12)
at repl:1:1
at realRunInThisContextScript (vm.js:22:35)
at sigintHandlersWrap (vm.js:98:12)
at ContextifyScript.Script.runInThisContext (vm.js:24:12)
at REPLServer.defaultEval (repl.js:313:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
第四次:
Trace
at factorial (repl:2:9)
at factorial (repl:7:12)
at factorial (repl:7:12)
at factorial (repl:7:12)
at repl:1:1
at realRunInThisContextScript (vm.js:22:35)
at sigintHandlersWrap (vm.js:98:12)
at ContextifyScript.Script.runInThisContext (vm.js:24:12)
at REPLServer.defaultEval (repl.js:313:29)
at bound (domain.js:280:14)
設想,如果傳入的參數值特別大,那么這個調用棧將會非常之大,最終可能超出調用棧的緩存大小而崩潰導致程序執行失敗。那么如何解決這個問題呢?使用尾遞歸。
尾遞歸
尾遞歸是一種遞歸的寫法,可以避免不斷的將函數壓棧最終導致堆棧溢出。通過設置一個累加參數,並且每一次都將當前的值累加上去,然后遞歸調用。
我們來看如何改寫之前定義factorial
函數為尾遞歸:
function factorial(n, total = 1) {
if (n === 0) {
return total
}
return factorial(n - 1, n * total)
}
factorial(3)
的執行步驟如下:
factorial(3, 1)
factorial(2, 3)
factorial(1, 6)
factorial(0, 6)
調用棧不再需要多次對factorial
進行壓棧處理,因為每一個遞歸調用都不在依賴於上一個遞歸調用的值。因此,空間的復雜度為o(1)而不是0(n)。
接下來,通過console.trace()
函數將調用棧打印出來。
function factorial(n, total = 1) {
console.trace()
if (n === 0) {
return total
}
return factorial(n - 1, n * total)
}
factorial(3)
很驚訝的發現,依然有很多壓棧!
// ...
// 下面是最后兩次對factorial的調用
Trace
at factorial (repl:2:9) // 3次壓棧
at factorial (repl:7:8)
at factorial (repl:7:8)
at repl:1:1 // 請忽略以下底層實現細節代碼
at realRunInThisContextScript (vm.js:22:35)
at sigintHandlersWrap (vm.js:98:12)
at ContextifyScript.Script.runInThisContext (vm.js:24:12)
at REPLServer.defaultEval (repl.js:313:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
Trace
at factorial (repl:2:9) // 最后第一調用再次壓棧
at factorial (repl:7:8)
at factorial (repl:7:8)
at factorial (repl:7:8)
at repl:1:1 // 請忽略以下底層實現細節代碼
at realRunInThisContextScript (vm.js:22:35)
at sigintHandlersWrap (vm.js:98:12)
at ContextifyScript.Script.runInThisContext (vm.js:24:12)
at REPLServer.defaultEval (repl.js:313:29)
at bound (domain.js:280:14)
這是為什么呢?
在Nodejs下面,我們可以通過開啟strict mode
, 並且使用--harmony_tailcalls
來開啟尾遞歸(proper tail call)。
'use strict'
function factorial(n, total = 1) {
console.trace()
if (n === 0) {
return total
}
return factorial(n - 1, n * total)
}
factorial(3)
使用如下命令:
node --harmony_tailcalls factorial.js
調用棧信息如下:
Trace
at factorial (/Users/stefanzan/factorial.js:3:13)
at Object.<anonymous> (/Users/stefanzan/factorial.js:9:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
Trace
at factorial (/Users/stefanzan/factorial.js:3:13)
at Object.<anonymous> (/Users/stefanzan/factorial.js:9:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
Trace
at factorial (/Users/stefanzan/factorial.js:3:13)
at Object.<anonymous> (/Users/stefanzan/factorial.js:9:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
Trace
at factorial (/Users/stefanzan/factorial.js:3:13)
at Object.<anonymous> (/Users/stefanzan/factorial.js:9:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
你會發現,不會在每次調用的時候壓棧,只有一個factorial
。
注意:尾遞歸不一定會將你的代碼執行速度提高;相反,可能會變慢。不過,尾遞歸可以讓你使用更少的內存,使你的遞歸函數更加安全 (前提是你要開啟harmony模式)。
那么,博主這里就疑問了:為什么尾遞歸一定要開啟harmony
模式才可以呢?
關於Fundebug
Fundebug專注於JavaScript、微信小程序、微信小游戲、支付寶小程序、React Native、Node.js和Java實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了7億+錯誤事件,得到了Google、360、金山軟件、百姓網等眾多知名用戶的認可。歡迎免費試用!
版權聲明
轉載時請注明作者Fundebug以及本文地址:
https://blog.fundebug.com/2017/06/14/all-about-recursions/