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:
This function takes three numbers, multiplies the numbers and returns the result.
Let’s create a curried version of the same function and see how we would call the same function and get the same result :
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:
It happens that all the cylinders are of height 100m.
You will see that you will repeatedly call this function with h
as 100
:
To resolve this, you curry the volume
function(like we did earlier):
We can define a specific function for a particular cylinder height:
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)
.