Friday, April 3, 2009

about factorial function

我承认,我被绕进去了。

// The Y combinator, applied to the factorial function
// https://javascriptlint.svn.sourceforge.net/svnroot/javascriptlint/trunk/spidermonkey/src/Y.js

function factorial(proc) {
    return function (n) {
        return (n <= 1) ? 1 : n * proc(n-1);
    }
}

function Y(outer) {
    function inner(proc) {
        function apply(arg) {
            return proc(proc)(arg);
        }
        return outer(apply);
    }
    return inner(inner);
}

print("5! is " + Y(factorial)(5));


// expand

Y(factorial)(5)
inner(inner)(5)
factorial(apply)(5)

(function (n) {
    return (n <= 1) ? 1 : n * proc(n-1);
})(5) // proc = apply

5 * apply(4)
5 * factorial(apply)(4)
5 * (function (n) {
        return (n <= 1) ? 1 : n * proc(n-1);
    })(4)
5 * (4 * apply(3))

2 comments:

Anonymous said...

我承认,完全看不懂

mapjeep said...

i am too~~~