Closures and currying
In functional programming, higher-order functions are nothing but functions that take in functions as arguments and/or return functions as return values.
In the above example, the
naive_add function took two arguments upfront.
We could also visualize
add as a higher-order function that takes in one argument (
x), and returns a function that adds its input (
The inner function is a closure. Closures are functions that keep track of variables from their containing scopes. In this case, the closure keeps track of the variable
x, even after it is returned to the outside world.
This enables us to write some elegant code like:
We expressed the
decrement functions in terms of the
add higher-order function.
Had we stuck with
naive_add function, the
decrement function would’ve looked more verbose:
Best of both worlds
Wouldn’t it be awesome if we had the simplicity of
naive_add and expressiveness of
Enter currying. As you’d have already guessed, it has nothing to do with Paneer butter masala.
bind method is used to curry functions:
This means that we donot have to explicity hand-code higher-order functions.
bind does that for us under the hood.
Note that the first argument to the
bind function is the receiver, which is consulted in case the function that we’re currying has references to
Let’s conclude by looking at a more tastier example of currying: