Archive for December 8th, 2008

Do you mean partial application?

December 8th, 2008

As I’ve been digging through more functional programming techniques, I often see people mention Curry functions. As it turns out, when a lot of people say “curry” they really mean Partial Application. For example, this page here about curry implementation in Python, or implementations in JavaScript. I did find one implementation in JavaScript that worked, but it’s rather long.

I came up with my own implementation in less than 10 lines of JavaScript code. Before I show it though, let’s define what we should expect. The follow are the JavaScript code we’re going to run, and the expected output are in the comments.

function add(a, b) {
    return a + b;
}

function add5(a, b, c, d, e) {
    return a + b + c + d + e;
}

function saySomething(x, y, z) {
    alert(x + y + z);
}

add.curry()(4)(6);
//--> 10

add5.curry()(1)(2)(3)(4)(5);
//--> 15

add5.curry()(1)(2);
//--> function with one parameter

add5.curry()(1)(2)(3)(4)(5)(6);
//--> TypeError: add5.curry()(1)(2)(3)(4)(5) is not a function

saySomething.curry()('Hello ')('World! ')('foo bar');
//--> Alert mssage "Hello World! foo bar" pops up

Remember that currying a function, say f:(X x Y) –> Z means that curry(f):X –> (Y –> Z). And for a function g with n arguments, curry(g) transforms the function g into a chain of n functions that each take exactly one argument.

So here is my implementation of the curry function.

Function.prototype.curry = function() {
    var savedArgs = [],  n = this.length, func = this;

    return (function(x) {
        savedArgs.push(x);
        if (savedArgs.length < n) return arguments.callee;
        else  return func.apply(null, savedArgs);
    });
};

Note that is utilizes anonymous functions in JavaScript, which recursively calls itself using the arguments.callee reference.