Function Composition in Python
Prerequisite: reduce(), lambda
Function composition is the way of combining two or more functions in such a way that the output of one function becomes the input of the second function and so on. For example, let there be two functions “F” and “G” and their composition can be represented as F(G(x)) where “x” is the argument and output of G(x) function will become the input of F() function.
Example:
def add(x):
return x + 2
def multiply(x):
return x * 2
print ( "Adding 2 to 5 and multiplying the result with 2: " ,
multiply(add( 5 )))
|
Output:
Adding 2 to 5 and multiplying the result with 2: 14
Explanation
First the add()
function is called on input 5. The add()
adds 2 to the input and the output which is 7, is given as the input to multiply()
which multiplies it by 2 and the output is 14
Better way to implement composition
There is a better way to implement the composition of Function. We can create a special function which can combine any two functions.
def composite_function(f, g):
return lambda x : f(g(x))
def add(x):
return x + 2
def multiply(x):
return x * 2
add_multiply = composite_function(multiply, add)
print ( "Adding 2 to 5 and multiplying the result with 2: " ,
add_multiply( 5 ))
|
Output:
Adding 2 to 5 and multiplying the result with 2: 14
Composing N number of function
We can compose any number of function by modifying the above method.
def composite_function(f, g):
return lambda x : f(g(x))
def add(x):
return x + 2
def multiply(x):
return x * 2
def subtract(x):
return x - 1
add_subtract_multiply = composite_function(composite_function(multiply,
subtract),
add)
print ( "Adding 2 to 5, then subtracting 1 and multiplying the result with 2: " ,
add_subtract_multiply( 5 ))
|
Output:
Adding 2 to 5, then subtracting 1 and multiplying the result with 2: 12
Now we will modify our composite_function to a function that can compose any number of function instead of two by using reduce() function from functools library.
from functools import reduce
def composite_function( * func):
def compose(f, g):
return lambda x : f(g(x))
return reduce (compose, func, lambda x : x)
def add(x):
return x + 2
def multiply(x):
return x * 2
def subtract(x):
return x - 1
add_subtract_multiply = composite_function(multiply,
subtract,
add)
print ( "Adding 2 to 5, then subtracting 1 and multiplying the result with 2: " ,
add_subtract_multiply( 5 ))
|
Output:
Adding 2 to 5, then subtracting 1 and multiplying the result with 2: 12
Explanation
The reduce()
function is taking first two function from *func and composing them using compose()
and then composing the third function to the previous composed function and so on. Here the multiply()
and subtract()
is composed first (multiply(subtract(x)) and then add() is composed (multiply(subtract(add(x))).
Last Updated :
07 Aug, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...