Function Compositions
tags: #python/documentation/python_functions
Function composition is a mathematical concept and a programming technique where two or more functions are combined to produce a new function.
- i.e., a method to combine two or more functions such that output of one function is passed as the input of the second function etc.
Mathematically, we can represent it as followed. Suppose that
Function compositions are used to create complex operations by combining simpler functions. They promote code reuse and modularity.
Python Example:
def square(x):
return x ** 2
def double(x):
return x * 2
# Function composition: square(double(x))
square_after_double = lambda x: square(double(x))
result = square_after_double(3)
print(result) # Output: 36
In this example, square_after_double is a new function that represents the composition of the square and double functions. When you call square_after_double(3), it first doubles the input (resulting in 6) and then squares the result (resulting in 36).