Sean Catchpole wrote:
> [ ...]
add = function (a) { return function (b) { return a+b } }
Now I can call add(3) and it will return function (b) { return 3+b }
[W]e can now call add(3)(7) and it will return 10.

And more to the point, you can store and use the function returned by the call to add(3), e.g.

    var newFunc = add(3);

For a JQuery example (and remember that I'm still new to jq, so I might be way off the mark here -- the code is entirely untested!), let's say we have many places where we want to toggle a class on hover, but that there are many different classes you want to toggle on different elements. You could do separate calls:

    $(".first").hover(function() {
        $(this).addClass("class1");
      },function(){
        $(this).removeClass("class1");
      }
    );

    $(".second").hover(function() {
        $(this).addClass("class2");
      },function(){
        $(this).removeClass("class2");
      }
    );

Or you could (and probably would) write a JQuery plugin:

jQuery.fn.hoverClass = function(className) {
    return this.each(function() {
        $(this).hover(function() {
            $(this).addClass(className);
          },function(){
            $(this).removeClass(className);
          }
        );
    }
};

and then call

    $(".first").hoverClass("class1");
    $(".second").hoverClass("class2");


But a third possibility would be to curry functions:

    addClass = function(className) {
        return function() {
            $(this).addClass(className);
        }
    });

    removeClass = function(className) {
        return function() {
            $(this).removeClass(className);
        }
    });

and to call it like this:

    $(".first").hover(addClass("class1"), removeClass("class1"));
    $(".second").hover(addClass("class2"), removeClass("class2"));


This has no advantage I can see here over the plugin method, but if you have a number of related functions that you need to call in multiple places, then you can store the result of the currying, and it could lead to much cleaner code.



This allows for lots of cleverness in use of functions and ultimately make functions far more reusable. I consider it a great advantage of functional programming. So as you can see, the same effect can be created, but it's tedious. I'm trying to come up with a trickier way so that it's not so painful to create a curried function in javascript.

Actually, I think this is quite easy in Javascript. If you look at the code listings in the Wikipedia article [1], Javascript has more succinct code than anything but scheme, and scheme's advantage mostly has to do with it's simpler syntax for functions.

  -- Scott

[1] http://en.wikipedia.org/wiki/Curried_function

Reply via email to