Imported Upstream version 1.0.0
[platform/upstream/js.git] / js / src / Y.js
1 // The Y combinator, applied to the factorial function
2
3 function factorial(proc) {
4     return function (n) {
5         return (n <= 1) ? 1 : n * proc(n-1);
6     }
7 }
8
9 function Y(outer) {
10     function inner(proc) {
11         function apply(arg) {
12             return proc(proc)(arg);
13         }
14         return outer(apply);
15     }
16     return inner(inner);
17 }
18
19 print("5! is " + Y(factorial)(5));