…without using arguments.callee!
I have read several “simple” introductions to the Y combinator (some of which are truly excellent), but I don’t know if I’ll ever manage to wrap my head completely around it, and it seems a bit verbose in use (at least in Javascript). It is a very cool concept though, and I decided to try implementing something similar (but possibly simpler) on my own. I managed to do this by using Javascript-specific stuff, specifically dicking around with arguments.
Technically, what I came up with is not exactly the same as the Y combinator, but its purpose is the same: To allow anonymous recursion. I’ve taken the liberty of calling it “the Z combinator” and it looks something like this:
function Z(func) {
var fun = function() {
return func.apply(null, [fun].concat([].slice.apply(arguments)));
};
return fun;
}
var fact = Z(function(rec, i) {
if (i === 0) {
return 1;
} else {
return i * rec(i-1);
}
});
fact(4); //24
// It can also be inlined:
Z(function(rec, i) { return i===0 ? 1 : i * rec(i-1); })(4); // 24
The Z combinator takes a function as an argument, and returns a new function that wraps the original and prepends itself to the argument list (if that makes any kind of sense). When recursing, the function should use call first parameter (rec, in this case) instead of calling itself by name. Thus, anonymous recursion! Maybe not very useful, but it was fun to do.
My name is Arne Martin Aurlien. I run this thing. Here’s a few facts about me:
Here’s a few things I have made: