以斐波那契数列为例

 

1, 1, 2, 3, 5, 8 。。。。。

 

function fb ( n ) {

  if (n<=0) {return 1};

  return fb(n-1) + fb(n-2)

}

 

优化后的尾递归

 

function fb(n , ac1=1, ac2 = 1) {

  if ( n <=1 ) {

    return ac2;

  }

  return fb(n-1, ac2, ac1 + ac2);

 

}

 

速度自己体会

 

下面是非严格模式下的尾递归优化

function sum (x, y) {

  if (y>0) {

    return sum(x+1, y-1)

  } else {

    return x;

  }

}

 

蹦床函数

function sum(x,y) {

  if (y>0) {

    return sum.apply(null, x + 1, y - 1);

  } else {

    return x;

  }

}

 

function tco(f) {

  var value;

  var active = false;

  var accumulated = [];

  return function accumulator() {

    accumulated.push(arguments);

    if (!active) {

      active = true;

      while(accumulated.length) {

        value = f.apply(this, accumulated.shift());

      }

      active = false;

      return value;

 

    }

  }

}

 

var sum = tco(function (x, y) {

  if (y>0) {

    return sum(x+1, y-i)

  } else {

    return x

  }

})

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-05
  • 2021-11-08
  • 2021-07-03
  • 2021-10-24
  • 2021-06-22
猜你喜欢
  • 2022-12-23
  • 2021-10-16
  • 2022-12-23
  • 2022-02-11
  • 2022-01-09
  • 2021-06-15
相关资源
相似解决方案