Search code examples
pythondependency-injectionfunctional-programmingsolid-principlescurrying

What is the benefit of using curried/currying function in Functional programming?


If you consider inner_multiply as an initializer of multiply, shouldn't you make them loosely coupled and DI the initializer (or any other way) especially if you require multiple initializers? Or am I misunderstanding the basic concept of curried function in FP?

def inner_multiply(x):
    def multiply(y):
        return x * y
    return multiply

def curried_multiply(x):
    return inner_multiply(x)

multiply_by_3 = curried_multiply(3)
result = multiply_by_3(5)
print(result)  # Output: 15 (3 * 5)

Solution

  • You can define an entirely generic curry function like this:

    def curry(f):
        return lambda x: lambda y: f(x, y)
    

    Assume, in order to reproduce the example in the OP, that you also define a multiply function like this:

    def multiply(x, y):
        return x * y
    

    You can now partially apply multiply using curry:

    >>> multiply_by_3 = curry(multiply)(3)
    >>> multiply_by_3(5)
    15
    

    This example immediately uses multiply_by_3, but the benefit is that you don't have to do that. Rather, you can partially apply the function in one place, pass that partially applied function around, and call it in an entirely different part of your code base.