我不想在 node/es2015 中玩尾调用优化,但我不断收到 RangeError: Maximum call stack size exceeded
。所以我尝试了一个非常简单的测试功能:
function countTo(n, acc) {
if(n === 0) {
return acc;
}
return countTo(n - 1, acc + n);
}
console.log(countTo(100000 , 0))
还是失败了。我试过在函数体内和文件顶部添加 'use strict';
。我试过使用 --harmony
和 --harmony-tailcalls
相同的功能在 Racket 中如预期的那样工作:
#lang racket
(define count-to
(lambda (n acc)
(cond
((= n 0) acc)
(else (count-to (- n 1) (+ acc n))))))
(count-to 100000000 0)
; ~> 5000000050000000
编辑:
正如@MatthieuLemoine 所建议的。它在 v6.5.0+ 中与 "use strict";
和 --harmony
或 --harmony-tailcalls
一起工作
最佳答案
使用 Node v6.5.0,以下工作:
function countTo(n, acc) {
'use strict';
if(n === 0) {
return acc;
}
return countTo(n - 1, acc + n);
}
console.log(countTo(100000 , 0));
使用 --harmony-tailcalls
标志运行:
node --harmony-tailcalls tco.js
关于javascript - 无法在 Node v6.4.0 中启用尾调用优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39617910/