Monday, October 28, 2019

Tail-Recursion, Tail-Call Optimization

https://stackoverflow.com/questions/33923/what-is-tail-recursion
https://stackoverflow.com/questions/310974/what-is-tail-call-optimization

Examples done after reading the answers in the 1st link above:

// 
//////////// Sum till n ////////////
//

// - normal recursion
function sumTo(n) {
  return (n == 0 ? 0 : (n+sumTo(n-1)));
}
var result = sumTo(10);
console.log(result);

// - tail recursion
function sumTo2(n) {
  return sumTo2_aux(n, 0);
}
function sumTo2_aux(n, acc) {
  return (n == 0) ? acc : sumTo2(n-1, acc+n);
}
var result2 = sumTo2(10);
console.log(result2);


//
//////////// Factorial ////////////
//

// - normal recursion
function factorial(n) {
  return (n == 1 ? 1 : n * factorial(n-1));
}
var factorial_result1 = factorial(10);
console.log(factorial_result1);

// - tail recursion
function factorial2(n) {
  return factorial2_aux(n,1);
}
function factorial2_aux(n, acc){
  return (n == 1 ? acc : n * factorial2_aux(n-1, acc));
}
var factorial_result2 = factorial2(10);
console.log(factorial_result2);

//

No comments:

Post a Comment

Followers

Blog Archive