4 ms·
You can if you want: var jp = function(last) { return formatNames2('John', 'Paul', last); }; var je = function(last) { return forma
by CrossEye 12y ago
You can if you want:
var jp = function(last) {
return formatNames2('John', 'Paul', last);
};
var je = function(last) {
return formatNames2('James', 'Earl', last);
};
var lh = function(last) {
return formatNames2('Lee', 'Harvey', last);
};
var c = function(middle, last) {
return formatNames('Clarabelle', middle, last);
};
But I find this cleaner:
var jp = formatNames2('John', 'Paul'};
var je = formatNames2('James', 'Earl'};
var lh = formatNames2('Lee', 'Harvey'};
var c = formatNames('Clarabelle'};
- Demiurge 12y agoShould you really have jp je lh and c at all than? Having so many different functions seems like a problem on its own, and maybe there should just be an array of names and a function iterating over them...
- CatMtKing 12y agoIt'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.
- Demiurge 12y agoI think I understand how it works, I just haven't seen examples that demonstrate why it is useful.
- ajuc 12y agoSay 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).
- CrossEye 12y agoA 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.