3 ms·
Sorry I'm not that familiar with this. What would be a good use-case for currying? The example doesn't feel that exciting... add4(1)(3)(5)(10) add4(1)
by gitgud 6y ago
Sorry I'm not that familiar with this. What would be a good use-case for currying?
The example doesn't feel that exciting...
add4(1)(3)(5)(10)
add4(1)(3,5)(10)
add4(1,3,5,10)
// 19
- ufo 6y agoThe add example is a bit boring because all the arguments are the same "kind". Partial evaluation is more interesting if the arguments are more independent. To borrow a contrived example from the Lodash docs, you can use partial evaluation to make a custom greeter function: https://lodash.com/docs/4.17.15#partial https://lodash.com/docs/4.17.15#partial https://lodash.com/docs/4.17.15#curry https://lodash.com/docs/4.17.15#curry function greet(greeting, name) { return greeting + ' ' + name; } var sayHelloTo = _.partial(greet, 'hello'); sayHelloTo('fred'); // => 'hello fred' var sayHi = _.partial(greet, 'hi'); greetFred('fred'); // => 'hi fred' Currying works similarly, except that the function by does the partial evaluation automatically if you call it with less arguments. var greet = _.curry(function(greeting, name) { return greeting + ' ' + name }) var sayHelloTo = greet('hello'); sayHelloTo('fred'); // => 'hello fred' var sayHi = greet('hi'); greetFred('fred'); // => 'hi fred'
- oweiler 6y agoCurrying becomes useful in tandem with functional composition.
- DiffProg 6y agoIndeed currying shows up most in functional programming world
- smichel17 6y agoIt's nice for any type of list iteration. I'll share my "match" function (for use when filtering) when I'm at my computer tomorrow.
- smichel17 6y agoIt's tomorrow somewhere… /** * These functions are intended to be used with array iteration methods * ------------------- * // Example data: * let e1 = { a: 1, b: 2, c: "C" }; * let e2 = { a: 2, b: 12, c: "D" }; * let myArray = [ e1, e2 ]; * * // Basic usage, matching a constant * myArray.filter(match({a: 1})); // [ e1 ] * myArray.filter(match({a: 3})); // [ ] * * // Matching multiple properties * myArray.filter(match({ a: 1, c: "C" })); // [ e1 ] * myArray.filter(match({ a: 1, c: "D" })); // [ ] * myArray.filter(matchAny({ a: 1, c: "D" })); // [ e1, e2 ] * * // If a function is provided, return the result of the function * // called with the corresponding property as its argument. * let belowTen = n => n < 10; * myArray.filter(match({ a: belowTen, b: belowTen })); // [ e1 ] * myArray.filter(matchAny({ a: belowTen, b: belowTen })); // [ e1, e2 ] * */ export const match = o1 => o2 => Object.entries(o1).every( ([k, v]) => typeof v === "function" ? v(o2[k]) : o2[k] === v ); export const matchAny = o1 => o2 => Object.entries(o1).some( ([k, v]) => typeof v === "function" ? v(o2[k]) : o2[k] === v );