that matt bone .com |

y-combinator in javascript

On Monday I was discussing the y combinator at Rossi’s. The next morning I wrote an example in scheme to send to my friends, but they don’t speak scheme. Sadly, this is tricky to write in python because of the lack of multi-line lambdas, but it’s damned easy in javascript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
    (function(x, thunk) {
     if(x==0) {
       return 0;
     } else {
       return x + thunk(x-1, thunk);
     }
    })(5, function(x, thunk) {
            if(x==0) {
              return 0;
            } else {
              return x + thunk(x-1, thunk);
            }
    });

See, there’s something to love about every language. And the beauty of this example is that you can probably type it write into the javascript console of you browser. REPL included.