Created
November 22, 2012 22:12
-
-
Save fabriceleal/4133116 to your computer and use it in GitHub Desktop.
Javascript macro for the Y combinator, using 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
// y-combinator | |
macro $y { | |
case ( $var ) => { | |
function(){ | |
return function(f){ | |
return f(f) | |
}(function(f){ | |
return $var(function(x){ | |
return f(f)(x); | |
}) | |
}); | |
}() | |
} | |
case ( function $pars $body ) => { | |
function(){ | |
return function(f){ | |
return f(f) | |
}(function(f){ | |
return function $pars $body(function(x){ | |
return f(f)(x); | |
}) | |
}); | |
}() | |
} | |
} | |
// factorial | |
var x = $y(function(fac){ return function(n){ if(n == 1) return 1; return n * fac(n-1); }}); | |
console.log(x(5)); | |
// This should also work | |
var fac_for_y = function(fac){ return function(n){ if(n == 1) return 1; return n * fac(n-1); }}; | |
var x2 = $y(fac_for_y); | |
console.log(x2(6)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment