Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // tailcall optimizer for javascript
- // written by mokrates
- // return new tailresult(func, this, arguments...); // <- mark tailcalls like so.
- function tailresult() { //func, this, ...
- this.func = arguments[0];
- this.that = arguments[1];
- this.args = new Array();
- for (i = 2; i<arguments.length; ++i)
- this.args[i-2] = arguments[i];
- }
- function tailcalling(f) { // decorator for tailcalling functions
- function decor() {
- res = f.apply(this, arguments);
- while (res instanceof tailresult)
- res = res.func.f.apply(res.that, res.args);
- return res;
- }
- decor.f = f
- return decor;
- }
- // example
- fak = tailcalling(function (acc, still) {
- document.writeln("" + acc + ", " + still);
- if (still == 1) return acc; // no tailcall? just normally return your value
- //else return fak(still*acc, still-1); // unmarked tailcall. 'too much recursion'
- else return new tailresult(fak, this, still*acc, still-1); // marked tailcall. works.
- });
- document.writeln(fak(1, 100000));
Advertisement
Add Comment
Please, Sign In to add comment