Created
February 12, 2015 03:30
-
-
Save levjj/b076a00304f782d877ac to your computer and use it in GitHub Desktop.
Tail Call Optimization with sweet.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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