Creating a Compose Function
Learn how to compose two or more functions.
We'll cover the following...
How to create a compose function
The composition examples in the previous lesson are quite procedural – we are composing functions by writing code that calls one function and then calls another function using the result from the first call.
One example is given below to refresh your memory.
Press + to interact
from functools import partialfrom operator import add, mulf = partial(add, 2)g = partial(mul, 3)x = 1print(f(g(x)))
We are writing code that describes how to do the composition rather than simply declaring that we want the composition to happen.
In the earlier chapter on closures, we created this simple compose function that accepted two functions and returned a function that composed them:
def compose2(f, g):
def fn(x):
return f(g(x))
return fn
Here we have renamed this function to compose2
. compose2
is a function that ...