How to Compose Functions in Python?

Estimated read time 2 min read

In Python, you can compose functions by using function composition techniques. Function composition allows you to create a new function by combining multiple existing functions together in a specific order. Here’s an example of how you can compose functions in Python:

def compose(*functions):
    def inner(arg):
        result = arg
        for f in reversed(functions):
            result = f(result)
        return result
    return inner

# Define some example functions
def add_one(x):
    return x + 1

def square(x):
    return x ** 2

def double(x):
    return x * 2

# Compose the functions
composed_function = compose(double, square, add_one)

# Test the composed function
result = composed_function(3)
print(result)  # Output: 32 (double(3 + 1) ** 2)

In this example, we define three simple functions: add_one(), square(), and double(). These functions perform basic mathematical operations.

We then define the compose() function, which takes a variable number of functions as arguments. Inside the compose() function, we define an inner function inner() that applies the functions in reverse order using a loop. The result of each function call is passed as the argument to the next function.

Finally, we create a composed function by calling compose() and passing the desired functions as arguments. In the example, we compose double(), square(), and add_one().

To test the composed function, we call it with an argument (e.g., 3) and print the result. The composed function applies each function in the defined order, resulting in the final output.

You can extend this example to include additional functions or modify the order of the composed functions to suit your specific needs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply