Skip to content

Instantly share code, notes, and snippets.

@levjj
Created February 12, 2015 03:30
Show Gist options
  • Save levjj/b076a00304f782d877ac to your computer and use it in GitHub Desktop.
Save levjj/b076a00304f782d877ac to your computer and use it in GitHub Desktop.
Tail Call Optimization with sweet.js
let function = macro {
rule { // proper tail call
$n ( $x (,) ... ) {
if ($b ... ) return $l:expr ;
return $n ( $y:expr (,) ...) ;
}
} => {
function $n ( $( $x ,) ... $xl) {
var tmp = {};
while (!($b ...)) {
$( tmp . $x = $y ) (;) ...
$( $x = tmp . $x) (;) ...
}
return $l;
}
}
rule { // otherwise
$n ( $x (,) ...) { $s ... }
} => {
function $n ( $x (,) ...) { $s ... }
}
}
function factorial(n) {
function f(n, i) {
if (n == 0) return i;
return f(n - 1, i * n);
};
return f(n, 1);
}
alert(factorial(4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment