Skip to content

Instantly share code, notes, and snippets.

@levjj
Last active August 29, 2015 13:56
Show Gist options
  • Save levjj/8817280 to your computer and use it in GitHub Desktop.
Save levjj/8817280 to your computer and use it in GitHub Desktop.
Computing factorial with sweet.js
macro fac {
case infix { $acc:lit | fac 0 } => { return #{$acc} }
case infix { $acc:lit | fac $n:lit } => {
var acc = #{$acc}, n = #{$n};
var res = acc[0].token.value * n[0].token.value;
var n1 = n[0].token.value - 1;
return withSyntax($res = [makeValue(res,n)],
$n1 = [makeValue(n1,n)]) {
return #{$res fac $n1}
}
}
case { fac $n } => { return #{1 fac $n} }
}
console.log(fac 1); // 1
console.log(fac 2); // 2
console.log(fac 3); // 6
console.log(fac 4); // 24
console.log(fac 5); // 120
console.log(fac 6); // 720
@levjj
Copy link
Author

levjj commented Feb 5, 2014

The last rule actually involves 8 macro expansions:

    console.log(fac 6);
    ->
    console.log(1 fac 6);
    ->
    console.log(6 fac 5);
    ->
    console.log(30 fac 4);
    ->
    console.log(120 fac 3);
    ->
    console.log(360 fac 2);
    ->
    console.log(720 fac 1);
    ->
    console.log(720 fac 0);
    ->
    console.log(720);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment