鍍金池/ 問答/Linux  HTML/ JavaScript使用尾遞歸沒效果?

JavaScript使用尾遞歸沒效果?

我學(xué)習(xí)函數(shù)式編程需要用到尾遞歸。發(fā)現(xiàn)沒起到作用。我的代碼是不是有錯(cuò)誤,還是谷歌瀏覽器不支持。

function currying(fn, n) {
  return function (m) {
    return fn.call(this, m, n);
  };
}

function tailFactorial(n, total) {
  "use strict";
  if (n === 1) {
    console.trace()
    return total
  };
  return tailFactorial(n - 1, n * total);
}

const factorial = currying(tailFactorial, 1);

factorial(5) // 120

我這樣寫代碼發(fā)現(xiàn)瀏覽器控制臺(tái)是這樣的

console.trace
tailFactorial    @    index.js:751
tailFactorial    @    index.js:754
tailFactorial    @    index.js:754
tailFactorial    @    index.js:754
tailFactorial    @    index.js:754
(anonymous)    @    index.js:743
(anonymous)    @    index.js:759
112    @    index.js:788
__webpack_require__    @    vendor.js:55
51    @    index.js:3679
__webpack_require__    @    vendor.js:55
92    @    index.js:4233
__webpack_require__    @    vendor.js:55
85    @    index.js:4034
__webpack_require__    @    vendor.js:55
81    @    index.js:3988
__webpack_require__    @    vendor.js:55
webpackJsonpCallback    @    vendor.js:26
(anonymous)    @    index.js:1

按照尾部?jī)?yōu)化應(yīng)該是這樣的

console.trace
tailFactorial    @    index.js:751
(anonymous)    @    index.js:743
(anonymous)    @    index.js:759
112    @    index.js:788
__webpack_require__    @    vendor.js:55
51    @    index.js:3679
__webpack_require__    @    vendor.js:55
92    @    index.js:4233
__webpack_require__    @    vendor.js:55
85    @    index.js:4034
__webpack_require__    @    vendor.js:55
81    @    index.js:3988
__webpack_require__    @    vendor.js:55
webpackJsonpCallback    @    vendor.js:26
(anonymous)    @    index.js:1

請(qǐng)問這是為什么?

回答
編輯回答
詆毀你

目前除了 Safari 都不支持尾遞歸

2017年4月24日 12:43