Guest User

tailcall optimization for javascript by mokrates

a guest
Feb 19th, 2012
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // tailcall optimizer for javascript
  2. // written by mokrates
  3.  
  4. // return new tailresult(func, this, arguments...); // <- mark tailcalls like so.
  5. function tailresult() { //func, this, ...
  6.     this.func = arguments[0];
  7.     this.that = arguments[1];
  8.     this.args = new Array();
  9.     for (i = 2; i<arguments.length; ++i)
  10.         this.args[i-2] = arguments[i];
  11. }
  12.  
  13. function tailcalling(f) {   // decorator for tailcalling functions
  14.     function decor() {
  15.         res = f.apply(this, arguments);
  16.         while (res instanceof tailresult)
  17.             res = res.func.f.apply(res.that, res.args);
  18.            
  19.         return res;
  20.     }
  21.     decor.f = f
  22.     return decor;
  23. }
  24.  
  25. // example
  26. fak = tailcalling(function (acc, still) {
  27.     document.writeln("" + acc + ", " + still);
  28.     if (still == 1) return acc; // no tailcall? just normally return your value
  29.     //else return fak(still*acc, still-1); // unmarked tailcall. 'too much recursion'
  30.     else return new tailresult(fak, this, still*acc, still-1); // marked tailcall. works.
  31. });
  32. document.writeln(fak(1, 100000));
Advertisement
Add Comment
Please, Sign In to add comment