3 ms·
That is by far the clearest implementation of the Y-combinator I've ever seen. And I'm not even a JavaScript programmer.
by dpkendal 15y ago
That is by far the clearest implementation of the Y-combinator I've ever seen. And I'm not even a JavaScript programmer.
- cygx 15y agoReally? What about function Y(f) { var g = f(function(arg) { return g(arg); }); return g; } The inner() function from Mozilla's implementation is actually unnecessary in languages that support lexical closures.
- ostso 15y agoThat's a fixed-point combinator, but it's not actually the Y combinator; in fact, it defeats much of the purpose of Y, since it's defined using explicit recursion, which Y is designed to avoid. If you just want a clear definition of a fixed-point combinator, you might as well use a non-strict language like Haskell, which doesn't require you to eta-expand g. Here's one recursive definition of fix in Haskell: fix f = f (fix f) This is probably the clearest definition you could ask for of what a fixed-point combinator actually is (other than something like "fix f = f (f (f (f (f ...", which is more difficult to give to a computer). Here's another one, which closer to what you gave in JavaScript (this is what you'll actually find in the Haskell standard libraries): fix f = let x = f x in x (Of course, due to type-checking, it's non-trivial to define the actual non-recursive Y in Haskell; you usually have to resort to using some type-level recursion. But in an untyped non-strict language you could define it easily enough.)