Hacker News new | ask | show | jobs
by Demiurge 4376 days ago
I think I understand how it works, I just haven't seen examples that demonstrate why it is useful.
1 comments

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.