Partially Applied Functions In JavaScript

I’m finding myself doing more and more functional programming with JavaScript lately – especially in recent days with this WinJS project I’m working on, and the heavy use of promises that it encourages. This feels a little odd to me, considering my current passion for building object-oriented JavaScript apps with Backbone. But at the same time, there’s something very natural about a functional style in JavaScript. There are a lot of fun things you can do with a functional style in JavaScript and I encourage you to explore it.

Partial Function Application

One of the tools that I’ve picked up in the process of exploring a functional style is partial function application, which according to Wikipedia, allows us to provide “a number of arguments to a function, producing another function of smaller arity.” (“Arity” is a fancy word for argument count of a function). Note that partial function application is not the same thing as “currying”. The two ideas may be similar, but they are definitely different and the two terms should not be interchanged.

What partial function application really means is that we can take a function that expects 2 parameters, and create a partially applied function that has the first parameter fixed. The result is itself a function that expects only one parameter. When calling that last function, the result of the original function is produced.

An example:

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

// partially apply this function with the "a" parameter set to 1
var partial = add.bind(null, 1);

// complete the function application by providing the "b" parameter
// with a value of "2". 1 + 2 = 3, so this results in 3.
partial(2); //=> 3

Here, we’re using the ECMAScript 5 standard of the “bind” function to do the partial application. The “bind” function serves two purposes: 1) to bind a function’s context (“this” argument) and 2) to create a partially applied function. 

The net result, when calling the “partial” function, is what you would expect to get by calling the original function with two parameters. This can be used any number of times, across any number of parameters. You can supply one or more arguments to bind to your partially applied function, and you can partially apply a partially applied function as well. Of course, this might get a little ridiculous after a while, but it can still be done.

Implementing Partial Application 

The most basic way to get partial application in to your code is to write for browsers and runtimes (like NodeJS and WinRT) that support ECMAScript-5. 

(Side note: Since I’m working with WinJS and WinRT in a Windows 8 runtime, I get to stick with raw ECMAScript 5 in my JavaScript. IE10 does a great job of implementing this standard, and it’s really a pleasure to write applications for this browser and the WinRT run time. The added benefit of not having to worry about cross-browser compatibility when building a WinJS application is also really refreshing.) 

But even if you’re not using a browser or runtime that supports ECMAScript-5 standards and the “bind” function, partial application is easy to do. Writing a function to do it yourself doesn’t take much effort, and there are plenty of implementations available to use – like this one from John Resig:

// John Resig's "curry" function from 
// http://ejohn.org/blog/partial-functions-in-javascript/
// which is unfortunately named, as this is not currying -
// it's partial function application.

Function.prototype.curry = function() {
    var fn = this, args = Array.prototype.slice.call(arguments);
    return function() {
      return fn.apply(this, args.concat(
        Array.prototype.slice.call(arguments)));
    };
  };


// a sample use

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

var partial = add.curry(1);

partial(2); //=> 3

Now you might not want to go and modify the core JavaScript “Function” prototype to add this (I wouldn’t personally). But don’t worry, you could easily modify that to work as a separate function call on it’s own. Or, you could use a library like Underscore.js, which provides partial application via the “bind” function on itself instead of modifying the Function prototype:

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

// using underscore.js "bind" function
var partial = _.bind(add, null, 1);

partial(2); //=> 3

There are probably a thousand other implementations of this around. I’m only listing these two for the sake of brevity in this blog post.

A Use Case For This

I’ve known about partial function application for quite some time now. But I’ve never had a reason to use it and never understood why it would be useful, or in what scenarios it might be a good idea. It just seemed like an academic exercise to me. In the WinJS/WinRT app that I’m building with the MS P&P group, though, I may have found a scenario where it makes sense and creates a much more clean expression of code than not using it.

This is some code that @bennage and I wrote for the sample WinJS/WinRT app that we’re building:

function buildThumbnails(files) {
    var localFolder = applicationData.current.localFolder;

    // Promise to build the thumbnails and return the list of local file paths
    var whenFolderCreated = localFolder.createFolderAsync(thumbnailFolderName, replaceExisting);

    return whenFolderCreated
        .then(function(folder){
          Tiles.copyImages(files, folder);
        })
        .then(Tiles.getFolderNamesFromFiles)
        .then(Tiles.update)
}

It’s not terribly bad. In fact, it’s quite terse and easy to read. It makes heavy use of promises and chains them together. Each of the function calls returns a promise, which facilitates the chained “then” calls. Except there’s that one call in the middle where an inline function is provided in order to get a second parameter passed to the function via a closure. I wanted to see what it would take to make this inline function go away, and partial application solved that problem for me:

function buildThumbnails(files) {
    var localFolder = applicationData.current.localFolder;

    // Promise to build the thumbnails and return the list of local file paths
    var whenFolderCreated = localFolder.createFolderAsync(thumbnailFolderName, replaceExisting);

    // partially apply the image copier to carry the files parameter with it,
    // allowing it to be used as a promise/callback that only needs to have
    // the `folder` parameter supplied.
    var copyThumbnailsToFolder = Tiles.copyImages.bind(null, files);

    return whenFolderCreated
        .then(copyThumbnailsToFolder)
        .then(Tiles.getFolderNamesFromFiles)
        .then(Tiles.update)
}

In this version, the inline function has been removed and a local variable has been provided in it’s place. That local variable is a partially applied function, using ECMAScript-5′s “bind” function. I apply the first parameter to the actual function call, and that returns a function that now only needs one parameter. Since the parameter that comes from the “then” call in the promise chain is the exact parameter that this partially applied function needs, I can supply this partially applied function to the “then” call and everything works as expected.

No, Really. An Actual Use Case For This?

Ok, this is a pretty trivial example and can easily be argued as unnecessary. The original code wasn’t that bad and may be easier to understand for some people. But the end result of the chained “then” statements has a certain beauty and elegance that I love. It’s got a distinct functional style and flow that makes it very easy for me to read, as if I’m looking at a sequence diagram for my code – and I can’t help but love that.


Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs SignalLeaf.com - the amazingly awesome podcast audio hosting service that everyone should be using, and WatchMeCode.net where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in Async, ECMAScript, Functional, Javascript, Underscore, WinJS. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://matthewmanela.com/ Matthew Manela

    I think the example usage you provide from the Partial functional implementation from John Resig’s blog is incorrect.

    The way that function works you need to pass in ‘undefined’ for the parameters you would like to be filled later.

    var partial = add.partial(1);
    console.log(partial(2) === 3); // = false
    console.log(partial(2) === NaN); // = true

    partial = add.partial(1,undefined);
    console.log(partial(2) === 3); // = true

    • http://mutedsolutions.com Derick Bailey

      D’oh! I copied the wrong function out of that article. Thanks for letting me know :) I updated the gist, but it might take a day or so for the caching to clear up.

  • http://davesquared.net David Tchepak

    Have you tried using function composition instead of chaining calls? I haven’t tried it in JS myself, but Liam recently pointed me to underscore’s compose function which looks quite interesting. AFAICT it would let you do something like:

    //pseudocode
    var buildThumbnails = _.compose(
       Tiles.update,
       Tiles.getFolderNamesFromFiles,
       Tiles.copyImages.bind(null, files));
     
    whenFolderCreated.then(buildThumbnails);

    Just another way to write the same thing I think, although a single composed function has the advantage of being able to be picked up and moved around / reused more easily than a chain of calls.

    • http://mutedsolutions.com Derick Bailey

      nice! wasn’t aware of that. in situations where you need to pass one function around, that would definitely be useful.

      in my case, i don’t need to pass anything around. i want the code to read as a list of steps “this, then this, then this, then this”.

      i’ll have to keep “compose” in mind, though. will be very useful.

      • http://davesquared.net David Tchepak

        I get what you mean, although compose is still a list of steps:

        _.compose(a, b, c)(x) == a(b(c(x)))
        // Which is the same as
        var resultC = c(x)
        var resultB = b (resultC)
        var resultA = a ( resultB )

        While “then” reads naturally to imperative programmers like me, I’m aware that learning to “speak” FP will probably make composition seem just as natural. I’m trying to learn this at the moment, as I feel being able to think in terms of composition will give me additional ways of thinking about problems.

        For example, it may lead me to think of testing the composed “buildThumbnails” function separately from the async “whenFolderCreated” function, where I previously may have stubbed out the “localFolder.createFolderAsync” call.

        You can also write a flipped compose function to compose left-to-right instead of right-to-left for cases where that reads more naturally.

        Obviously none of this is to say that the chained calls are wrong, just that I’ve found it interesting and potentially useful to also think in terms of composition, so thought I’d share. :)

        Cheers,
        Dave

  • dan

    https://gist.github.com/3151016#file_3.js

    Does partial need to bind to add?

    var partial = _.bind(add, null, 1);

    • http://mutedsolutions.com Derick Bailey

      oops! yes. :)

      i updated the gist to correct this. it will take a day or two for the cache to clear and be reflected in this post.

  • Andrew Kirkegaard

    How would you bind the second attribute?
    Like: var render = _.bind(Backbone.Marionette.Renderer.render, null, undefined, this.options.x);
    Backbone.Marionette.TemplateCache.get(this.template)
    .then(render)
    .then(function (html) { that.$el.html(html); }) ;
    In order to partially apply Marionette’s render to the serialized data, and then run when the Template is received.