简体   繁体   English

我如何编写一个递归函数,该函数对使用尾调用优化(TCO)的数字数组求和?

[英]How would I write a recursive function that sums an array of numbers that uses tail call optimization (TCO)?

So I wrote this function that sums an array of numbers using recursion. 所以我编写了这个函数,使用递归对一组数字进行求和。 How would I make this tail call optimized? 如何优化尾调用?

function sum(array) {
  if (array.length === 0) {
    return 0;
  } else {
    return array[0] + sum(array.slice(1));
  }
}

sum([1, 2, 3, 4, 5]); // 15

A TCO function needs to return a function call, which replaces the last stack item and prevents the stack to grow. TCO函数需要返回一个函数调用,它会替换最后一个堆栈项并阻止堆栈增长。

Therfore you need to store the total as well in the function as parameter and hand over this value at the ent of the recursion. 因此,您需要将total也存储在函数中作为参数,并在递归时移交此值。

 function sum(array, total = 0) { if (array.length === 0) { return total; } return sum(array.slice(1), total + array[0]); } console.log(sum([1, 2, 3, 4, 5])); // 15 

Using Array.prototype.reduce() there is no need to do a recursive function: 使用Array.prototype.reduce()不需要执行递归函数:

 const result = [1, 2, 3, 4, 5].reduce((a, c) => a + c, 0); // 15 console.log(result); 

Just use a ternary operator like so: 只需使用三元运算符,如下所示:

 const sum = array => array.length ? array[0] + sum(array.slice(1)) : 0; console.log(sum([1, 2, 3, 4, 5])); // 15 

You can also use Array.prototype.reduce to avoid recursion: 您还可以使用Array.prototype.reduce来避免递归:

 const sum = array => array.reduce((acc, curr) => acc + curr, 0); console.log(sum([1, 2, 3, 4, 5])); 

You can't, tail call optimization (TCO) is not supported in most of browser. 你不能,大多数浏览器都不支持尾调用优化(TCO)。 You can see support info here . 您可以在此处查看支持信息。

You can always use for loop. 你总是可以使用for循环。 for loop has higher performance in most of situation. for循环在大多数情况下具有更高的性能。

 function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值} function sum_1(arr) { var s = 0; for (var i = 0; i < arr.length; i++) { s += arr[i]; } return s; } function sum_2(arr){ return arr.reduce((a, c) => a + c, 0); } var arr = []; for (var i = 0; i < 10000000; i++) { arr[i] = getRandomInt(0,100); } let t0 = window.performance.now(); sum_1(arr); // 15 let t1 = window.performance.now(); console.log("sum_1 executed time : " + (t1 - t0) + " ms"); let t2 = window.performance.now(); sum_2(arr); // 15 let t3 = window.performance.now(); console.log("sum_2 executed time : " + (t3 - t2) + " ms"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何在 ES5 中的递归匿名函数上应用 TCO(尾调用优化) - How do i apply TCO(Tail Call Optimiztion) on recursive anonymous Function in ES5 尾调用优化 (TCO) 在 Safari 中不起作用 - Tail call optimization (TCO) not working in Safari ES6类中的递归方法是否利用了TCO(尾调用优化)? - Do recursive methods in ES6 classes take advantage of TCO (Tail Call Optimization)? 如何记录返回 function 调用的 function 调用(用于尾调用优化) - How to document a function that returns a function call (for tail call optimization) 是否有任何 JavaScript 引擎尾调用 (TCO) 优化? - Are any JavaScript engines tail call (TCO) optimized? 尾调用优化递归函数 - Tail Call Optimizing recursive function 给定一个带数字的数组,如何编写一个递归函数,当2个元素加到目标时,它会在数组中找到索引? - Given an array with numbers, how can I write a recursive function that finds indices in the array when 2 elements add up to a target? 是否优化了阶乘尾叫(TCO)的延续样式实现? - Is continuation style implementation of factorial tail call optimized (TCO)? 对数组求和的函数(包括数字作为字符串) - Function that sums array numbers (including numbers as strings) 尾部呼叫优化javascript - tail call optimization javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM