public
Last active

Javascript macro for the Y combinator, using sweet.js

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
// 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));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.