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.

Mathematically, we can represent it as followed. Suppose that F(x),G(x) are two separate functions; their composition can be represented as the following where x, is the argument and output of G(x) that will become the input of F(x)

F(G(x))
How is this different from Nested Function?

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).

Powered by Forestry.md