Mmm, curry

Currying and partial function application are two concepts from functional programming that sound far more complicated than they really are.

One of the times I find myself wishing it were more convenient to do in JavaScript is when trying to escape callback hell by extracting functions:

var shared = new Shared();
doSomething(shared).then(function(result) {
    somethingElse(shared, result);
});

It would be nice to be able to go straight to this:

var shared = new Shared();
doSomething(shared).then(somethingElse);

Of course this wouldn’t work, as the somethingElse function expects 2 parameters instead of just one.

If JavaScript supported partial application in the way that the ML family of languages do, then we could say:

doSomething(shared).then(somethingElse(shared));

But that means something entirely different in JavaScript: the result of the function being executed with one argument would be passed in.

It’s relatively straightforward to write a curry function and use that, but there is an alternative; returning an appropriate function from the called method:

var shared = new Shared();
doSomething(shared).then(somethingElse(shared));

function somethingElse(shared, result) {
    return function(result) {
        // do something with shared & result
    };
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s