Closures and Partial Application
Learn how to use closures to create partial applications of functions.
We'll cover the following...
This is the first of two chapters that will cover some additional techniques used in functional programming.
In this chapter, we will revisit closures and composition and also look at partial application and currying. These are all ways to create a new function from an existing function.
In the next chapter, we will look at functors and monads. In addition, we will look at some functions offered by the PyMonad
library that can do a lot of the work for you.
Closures
We have looked at closures quite extensively, with a whole chapter devoted to them, so all we will do here is a quick recap. A closure occurs when:
- A function includes an inner function.
- The outer function returns the inner function.
- The inner function references some variables within the scope of the outer function.
The returned inner function is called a closure. It can still access the values defined within the scope of the outer function, even though the outer function, itself, is no longer active.
Partial application
Partial application is a way of creating a new function based on an existing function but with some of the parameters already filled in with a chosen value.
For example, here is a closure that creates partial applications of the standard function, max
:
def maxn(n):def f(x):return max(n, x)return f
Now, for example, if we call maxn(0)
, it will return a closure of f(x)
, with the values of n
fixed at 0. In other words, it will return a function that calculates max(0, x)
. You can see it in action below.
def maxn(n):def f(x):return max(n, x)return fmax0 = maxn(0)print(max0(3)) # Equivalent to max(0, 3) -> 3print(max0(-1)) # Equivalent to max(0, -1) -> 0
We have created our new function, max0
, and a couple of test cases to prove that it does, indeed, calculate max(0, x)
. In effect, it replaces any negative value with 0.
Here is an example using our partial application with map
. In this case, we are using maxn
to create an anonymous function that gets used in the map
call. ...