on
Concept of Currying
“Currying is the process of turning a function with multiple arity into a function with less arity” — Kristina Brainwave
In simple words, currying is a method in programming in which we can transform a function with multiple arguments into a nested functions. It returns a new function that expects the next argument.
So, currying transforms a function with multiple arguments into a series of functions each taking a single argument.
Let’s look at a simple example:
function multiply(a, b, c) { return a * b * c;}
This function takes three numbers, multiplies the numbers and returns the result.
multiply(1,2,3); // 6
Let’s create a curried version of the same function and see how we would call the same function and get the same result :
function multiply(a) {
return (b) => {
return (c) => {
return a * b * c
}
}
}
multiply(1)(2)(3) // 6
Above as you can see we have turned the multiply(1,2,3) function call to multiply(1)(2)(3) multiple function calls.
Is Currying useful?
Avoid frequently calling a function with the same argument:
For example, we have a function to calculate the volume of a cylinder:
function volume(l, w, h) { return l * w * h;}
It happens that all the cylinders are of height 100m.
You will see that you will repeatedly call this function with h
as 100
:
volume(200,30,100) // 20030100
volume(32,45,100); //144000l
To resolve this, you curry the volume
function(like we did earlier):
function volume(h) {
return (w) => {
return (l) => {
return (l * w * h)
}
}
}
We can define a specific function for a particular cylinder height:
const CylinderHeight = volume(100);
CylinderHeight(200)(30); // 600,000l
Conclusion
Currying is a transform that makes function(a,b,c)
as function(a)(b)(c)
.
Currying allows to easily get partials function. As we’ve seen in the volume example: the universal function log(h, w, l)
after currying gives us partials when called with one argument like function(h)
or two arguments function(w, l)
.