尾递归及尾递归优化

以斐波那契数列为例

 

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

  }

})

 

posted @ 2017-02-15 17:08  她在村口等我  阅读(218)  评论(0编辑  收藏  举报