Hacker News new | ask | show | jobs
by CatMtKing 4376 days ago
It's a toy example; he's just trying to show how currying works, rather than why you should use it.

If anything, it does show that one useful thing about partial application is that you can write a generic function (formatNames) and then make it more specific (formatNames("John")) without repeating yourself.

1 comments

I think I understand how it works, I just haven't seen examples that demonstrate why it is useful.
Say you want to calculate distances from origin to each point in array, and keep only these greater than R.

Using fors and ifs:

    var origin = Point(0, 0);
    var R = 100;
    var result = [];
    for (var i : array) {
        tmp = distance(array[i], origin);
        if (tmp>R) {
           result.append(tmp);
        }
    }
Without currying (nobody would write it that way):

    var origin = Point(0, 0);
    var R = 100;
    result = filter( map(array, function (x) { return distance(x, origin); }),
                     function (x) { return greater(x, R);} );
With currying it almost reads like SQL:

    var origin = Point(0, 0);
    var R = 100;
    result = filter( map(array, distance(origin)), greater(R) );
It's useful for functions that you predict will be used many times with one of the arguments the same. Yes, it's just syntactic sugar, but it sometimes makes code clearer (especially when literal function syntax is as verbose as in javascript).
A nice example. Thank you.

I just want to note that in Ramda, because of it's strong insistence on a data-last API (which makes the currying easier), this would be written in this order:

    result = filter(greater(R), map(distance(origin), array));
But it's precisely the same idea.