Currying and Partial Applications are always confusing topics and originated from mathematics and computer science.
So it’s our responsibility to understand these concepts with the clear differences and use it effectively in our projects to achieve the benefit of lazy evaluation.
Currying is the process of taking a function with multiple arguments, and turning into the sequence of functions each with a single argument.
Let’s take the below example:
We have a generic function called formatDate which takes date_format and timestamp both as arguments and returns the formatted date.
Like the above example, we have multiple timestamps to be formatted using the same date_format. so every time while calling the formatDate function we need to pass the fresh timestamp but the same date_format again and again as it’s not changing frequently throughout our code.
Let’s use the function currying technique and change the above way of writing the formatDate function,
Function Currying example:
In this example, using the function currying process we curried our formatDate function. So initially it will take timeStamp as an argument and return another function. This returned function can be used to format multiple timestamps in our code until there is change of date_format.
So now every time when we need to format our timestamps, we no need to pass the date_format again and again because it’s already pre-defined in our curried function.
Partial application is the process of fixing the number of arguments to a function, producing another function of smaller arity (i.e no of arguments or operands taken by a function).
It is the same as Currying, but the returned functions may take one or more arguments.
In Currying, the no of functions returned is equal to no of arguments to complete the entire function evaluation, but that is not in the case of partial application function.
Let’s take the same above example, and consider now it’s taking one more extra argument called timeZone that used to append in our formatted date.
In this example, the formatDate function takes 2 pre-defined arguments and returns the function to get the timeStamp. Hence no of function calls is not equal to the no arguments needed to complete this evaluation.
Both of these techniques help to do the lazy evaluations in our code. Utilising these concepts in our day to day code, makes our code cleaner and simpler. It also avoids the repetition of passing the same arguments again and again.