Composing functions is a fundamental technique in functional programming and can be very useful in Python for creating complex data processing pipelines.
Here's an example of how you can compose functions in Python:
def double(x): # Function to double a number return x * 2def square(x): # Function to square a number return x ** 2def compose(f, g): # Function to compose two functions return lambda x: f(g(x))# Example usage:f = compose(square, double)result = f(5)print(result) |
In this example, we define two functions double and square that double and square a number, respectively. We then define a compose function that takes two functions as input and returns a new function that applies the input functions in sequence.
The compose function works by returning a lambda function that applies the second function g to the input value x, and then applies the first function f to the result of g(x).
Finally, we demonstrate how to use the compose function to create a new function f that first doubles its input value and then squares the result. We then apply f to the value 5 and print the result.
This approach allows us to create complex data processing pipelines by composing simple functions together. By breaking down the processing into small, reusable functions, we can create pipelines that are easy to understand and maintain, and that can be modified or extended as needed.