FP's Secret Sauce
An in-depth look at currying and its advantages. (5 min. read)
We'll cover the following...
Currying
I hope the last section gave you a taste of currying, as we’re dipping a bit more into it here.
Its main benefit is code reuse. Curried functions have a better chance of being useful in different scenarios, thus making them DRYer.
Let’s say you have an add function
What happens if you don’t give add its required parameters? What if you give too little?
Not fun. You know this leads to weird bugs, especially in JavaScript where we do anything and everything. The problem sort of goes away when you curry add.
Your eyes don’t deceive you, curriedAdd(2) returns a function. It will keep returning a function until you supply the last parameter, y.
Not Entirely Textbook
According to the FP books, currying means you return one new function per expected parameter.
So if you have an add3 or greet function
“Properly” currying them looks like this
But let’s be honest, this sucks in JavaScript. I don’t want to call my functions like this
Thankfully Ramda’s curry supports either style. You can use them like above or give all the arguments at once.
Summary
-
Curried functions keep returning functions until all required parameters are given.
-
This lets you partially apply a function and create more specialized versions.
-
“Properly” curried functions return one function per argument.
(a) => (b) => (c)instead of(a, b, c). -
But they’re a bit impractical so Ramda lets you supply them normally, or one at a time.