This is the fourth part of the functional programming series. If you have missed the previous one, start here.
Series pit stops
- f(1) — Basics, Understanding Functions
- f(2) — Functions in Kotlin, Pure functions
- f(3) — Function composition
- f(4) – Currying function (you are here)
In this pit stop, we’ll take a brief look at how we write or represent currying functions in Kotlin.
- Basic programming knowledge
- School mathematics
- Previous pit stop
Since we talked just f(x), here x can be treated as an argument in programming perspective. So our examples before were only for functions with one argument. How do we compose for functions with multiple arguments?
In FP concept, a function cannot have multiple arguments. Shocked? don’t be. If you recall before, a function is just a map from one source set to another. It’s not a map from multiple source sets to target sets. But on the other hand, a product of 2 sets can result in a set. Such a product of sets, resulting a function which is a set, can resemble like a function of multiple arguments.
Here the element x is a pair of 2 elements. Let’s take it as 33 and 48.Here the function of 2 sets are called Tuple.
Currying a function is nothing but an operation where we apply one function at a time, pass the result to the next and so on, till we reach the result. Let’s take the same example f(x, y) = 2x + y
This can also be written as
Let’s consider f(x) as g. Then,
When f(x) is applied to be g, then the value x in 2x + y is a constant. It’s not a variable to be substituted with. Hence,
In other words, when we apply x for the function f, we get a resulting function g which is applied to y. This is process is called currying a function.
When we represent tuple in Kotlin (also NOT known as function with 2 parameters), we just pass the result to next function. Like
The above represents : A function, that takes an integer as a parameter (Int) and returns a function of (Int) -> Int
It’s time for some examples of currying in Kotlin. Let’s take the above functions and try to represent in Kotlin.
Now, like our previous pitstop – what if we write a generalized function that can curry two functions?
In short, currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions. It returns a new function that expects the next argument inline. It keeps returning the function until it exhausts the arguments.
If you think you have learned something new or if you like this series or you want to boost my morale, please share the post. Thanks a lot for reading this article. Hope you have enjoyed this series!