Preface
While I don’t consider myself a functional programming guru, all those hours spent in Haskell, Lisp and Scheme definitively changed my way of programming. So, after seeing a lot of unnecessarily complex implementations of function composition in Python on the Web, I decided to write this article to present a simple yet powerful solution that covers all use cases. If you are familiar with function composition, you may want to go to the solution.
Composing two functions
Function composition is a way of combining functions such that the result of each function is passed as the argument of the next function. For example, the composition of two functions f and g is denoted f(g(x)). x is the argument of g, the result of g is passed as the argument of f and the result of the composition is the result of f.
Let’s define compose2, a function that takes two functions as arguments (f and g) and returns a function representing their composition:
- def compose2(f, g):
- return lambda x: f(g(x))
Composing n functions
Now that we know how to compose two functions, it would be interesting to generalize it to accept n functions. Since the solution is based on compose2, let’s first look at the composition of three functions using compose2.
Do you see the pattern? First, we compose the first two functions, then we compose the newly created function with the next one and so on. Let’s write this in Python.
- import functools
- def compose(*functions):
- def compose2(f, g):
- return lambda x: f(g(x))
- return functools.reduce(compose2, functions, lambda x: x)
- def compose(*functions):
- return functools.reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x)
Note that functools.reduce is also called fold.
Multiple-argument functions
The reason why implementations get complex is because they support multiple-argument functions. But there is no need to do so, because any function can be transformed to a one-argument function using higher-order functions such as functools.partial, decorators or our own functions.
If you want to learn about functional programming in Python, I recommend this document.
沒有留言:
張貼留言