Drkcore

17 02 2011 javascript Tweet

Javascriptで末尾最適化

元ネタはspencertipping / js-in-ten-minutes

Function.prototype.tail = function () {return [this, arguments]};
Function.prototype.call_with_tco = function () {
  var c = [this, arguments];
  var escape = arguments[arguments.length-1];
  while(c[0] !== escape)
    c = c[0].apply(this, c[1]);
  return escape.apply(this,c[1]);
};

// var sum  = function (n,acc) { return n > 0 ? sum(n-1,acc+n) : acc};
var sum2 = function (n,acc,k) { return n > 0 ? sum2.tail (n-1,acc+n,k) : k.tail (acc);};
var id   = function (x) {return x};
console.log(sum2.call_with_tco(100000,0,id));

これはDelimited Continuationになっているらしい。コードの動きは分かるけど継続とDelimited Continuationの違いが良くわからん。

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021