JavaScript中的遞歸-創(chuàng)新互聯(lián)

譯者按: 程序員應(yīng)該知道遞歸,但是你真的知道是怎么回事么?

創(chuàng)新互聯(lián)建站從2013年開始,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目網(wǎng)站設(shè)計(jì)制作、網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元犍為做網(wǎng)站,已為上家服務(wù),為犍為各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:18980820575
  • 原文: All About Recursion, PTC, TCO and STC in JavaScript
  • 譯者: Fundebug

為了保證可讀性,本文采用意譯而非直譯。

遞歸簡(jiǎn)介

一個(gè)過(guò)程或函數(shù)在其定義或說(shuō)明中有直接或間接調(diào)用自身的一種方法,它通常把一個(gè)大型復(fù)雜的問(wèn)題層層轉(zhuǎn)化為一個(gè)與原問(wèn)題相似的規(guī)模較小的問(wèn)題來(lái)求解,遞歸策略只需少量的程序就可描述出解題過(guò)程所需要的多次重復(fù)計(jì)算,大大地減少了程序的代碼量。

我們來(lái)舉個(gè)例子,我們可以用4的階乘乘以4來(lái)定義5的階乘,3的階乘乘以4來(lái)定義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函數(shù):

factorial n = factorial (n-1)  * n
factorial 0 = 1

在遞歸的例子中,從第一個(gè)調(diào)用factorial(5)開始,一直遞歸調(diào)用factorial函數(shù)自身直到參數(shù)的值為0。下面是一個(gè)形象的圖例:
JavaScript中的遞歸

遞歸的調(diào)用棧

為了理解調(diào)用棧,我們回到factorial函數(shù)的例子。

function factorial(n) {
    if (n === 0) {
        return 1
    }

    return n * factorial(n - 1)
}

如果我們傳入?yún)?shù)3,將會(huì)遞歸調(diào)用factorial(2)、factorial(1)factorial(0),因此會(huì)額外再調(diào)用factorial三次。

每次函數(shù)調(diào)用都會(huì)壓入調(diào)用棧,整個(gè)調(diào)用棧如下:

factorial(0) // 0的階乘為1 
factorial(1) // 該調(diào)用依賴factorial(0)
factorial(2) // 該調(diào)用依賴factorial(1)
factorial(3) // 該掉用依賴factorial(2)

現(xiàn)在我們修改代碼,插入console.trace()來(lái)查看每一次當(dāng)前的調(diào)用棧的狀態(tài):

function factorial(n) {
    console.trace()
    if (n === 0) {
        return 1
    }

    return n * factorial(n - 1)
}

factorial(3)

接下來(lái)我們看看調(diào)用棧是怎樣的。
第一個(gè):

Trace
    at factorial (repl:2:9)
    at repl:1:1 // 請(qǐng)忽略以下底層實(shí)現(xiàn)細(xì)節(jié)代碼
    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)

你會(huì)發(fā)現(xiàn),該調(diào)用棧包含一個(gè)對(duì)factorial函數(shù)的調(diào)用,這里是factorial(3)。接下來(lái)就更加有趣了,我們來(lái)看第二次打印出來(lái)的調(diào)用棧:

Trace
    at factorial (repl:2:9)
    at factorial (repl:7:12)
    at repl:1:1 // 請(qǐng)忽略以下底層實(shí)現(xiàn)細(xì)節(jié)代碼
    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)

現(xiàn)在我們有兩個(gè)對(duì)factorial函數(shù)的調(diào)用。

第三次:

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)

設(shè)想,如果傳入的參數(shù)值特別大,那么這個(gè)調(diào)用棧將會(huì)非常之大,最終可能超出調(diào)用棧的緩存大小而崩潰導(dǎo)致程序執(zhí)行失敗。那么如何解決這個(gè)問(wèn)題呢?使用尾遞歸。

尾遞歸

尾遞歸是一種遞歸的寫法,可以避免不斷的將函數(shù)壓棧最終導(dǎo)致堆棧溢出。通過(guò)設(shè)置一個(gè)累加參數(shù),并且每一次都將當(dāng)前的值累加上去,然后遞歸調(diào)用。

我們來(lái)看如何改寫之前定義factorial函數(shù)為尾遞歸:

function factorial(n, total = 1) {
    if (n === 0) {
        return total
    }

    return factorial(n - 1, n * total)
}

factorial(3)的執(zhí)行步驟如下:

factorial(3, 1) 
factorial(2, 3) 
factorial(1, 6) 
factorial(0, 6)

調(diào)用棧不再需要多次對(duì)factorial進(jìn)行壓棧處理,因?yàn)槊恳粋€(gè)遞歸調(diào)用都不在依賴于上一個(gè)遞歸調(diào)用的值。因此,空間的復(fù)雜度為o(1)而不是0(n)。

接下來(lái),通過(guò)console.trace()函數(shù)將調(diào)用棧打印出來(lái)。

function factorial(n, total = 1) {
    console.trace()
    if (n === 0) {
        return total
    }

    return factorial(n - 1, n * total)
}

factorial(3)

很驚訝的發(fā)現(xiàn),依然有很多壓棧!

// ...
// 下面是最后兩次對(duì)factorial的調(diào)用
Trace
    at factorial (repl:2:9) 
    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下面,我們可以通過(guò)開啟strict mode, 并且使用--harmony_tailcalls來(lái)開啟尾遞歸(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

調(diào)用棧信息如下:

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)

你會(huì)發(fā)現(xiàn),不會(huì)在每次調(diào)用的時(shí)候壓棧,只有一個(gè)factorial。

注意:尾遞歸不一定會(huì)將你的代碼執(zhí)行速度提高;相反,可能會(huì)變慢。不過(guò),尾遞歸可以讓你使用更少的內(nèi)存,使你的遞歸函數(shù)更加安全 (前提是你要開啟harmony模式)。

那么,博主這里就疑問(wèn)了:為什么尾遞歸一定要開啟harmony模式才可以呢?

關(guān)于Fundebug

Fundebug專注于JavaScript、微信小程序、微信小游戲、支付寶小程序、React Native、Node.js和Java實(shí)時(shí)BUG監(jiān)控。 自從2016年雙十一正式上線,F(xiàn)undebug累計(jì)處理了7億+錯(cuò)誤事件,得到了Google、360、金山軟件、百姓網(wǎng)等眾多知名用戶的認(rèn)可。歡迎免費(fèi)試用!

JavaScript中的遞歸

版權(quán)聲明

轉(zhuǎn)載時(shí)請(qǐng)注明作者Fundebug以及本文地址:
https://blog.fundebug.com/2017/06/14/all-about-recursions/

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。

當(dāng)前文章:JavaScript中的遞歸-創(chuàng)新互聯(lián)
網(wǎng)站地址:http://bm7419.com/article46/hcshg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作小程序開發(fā)、商城網(wǎng)站、服務(wù)器托管、外貿(mào)網(wǎng)站建設(shè)、域名注冊(cè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁(yè)設(shè)計(jì)