Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 393
Ando Avatar asked Feb 03 '26 21:02

Ando


1 Answers

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.

like image 81
Mark Seemann Avatar answered Feb 05 '26 10:02

Mark Seemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!