Javascript Y Combinator

Last Update

10/25/2002; 8:43:46 PM

A famous lambda trick, in Javascript:

// The Y Combinator
var Y=function (gen) {
 return function(f) {return f(f)}(
  function(f) {
   return gen(function() {return f(f).apply(null, arguments)})})}
 
// An example
var fact=Y(function(h){
 return function(n){
  return (n<2)?1:n*h(n-1)}});

Not that you actually need a Y combinator of course. This is a shorter version the anonymous factorial function:

function(n){return (n<2)?1:n*arguments.callee(n-1)}