Deriving the y-combinator in Javascript

I wrote the Javascript here, but did not invent the algorithms. View the source for the code, or view it below if your browser supports applying CSS to <script> elements. Check your Javascript console for the tests. If you don't have a console.log function, then it'll use document.write instead, and the output will be at the bottom.

One can learn quite a bit about Javascript by practicing with Lisp patterns. If it can be done in Lisp, it can usually be done in Javascript, albeit with more characters. Conceptually, working with Lisp examples teaches one to see Javascript in a different light, and exposes the power of functional programming more directly. For those of us who have more experience in Javascript than we do in Lisp, transcribing can help in grokking these patterns, just as translating Don Quixote into English can help with one's Spanish.

You can argue that Lisp is better than Javascript for any number of very valid reasons. But the browser is the biggest deployment platform ever, and Javascript is the language we have for it, and it is quite a nice language, so we may as well learn to use its power.

Writing Javascript like this is probably not a good idea most of the time. It will scare your coworkers. JSLint will scold you. But it's fun as a workout once in a while.

There is of course more than one way to skin this cat, but the goal of this exercise is to work through the examples writing code that is as strictly functional as possible, not to create the one true ycombinator function for Javascript. Try to get every function down to a single return statement without any local vars.

Isaac Z. Schlueter, 2008-10-31

All code on this page © 2008 Isaac Z. Schlueter, licensed under the WTFPL. No rights reserved.