Sobes.tech
Junior — Middle

Explain the concept of function currying and its application in programming.

sobes.tech AI

Answer from AI

Currying is a technique of transforming a function with multiple arguments into a sequence of functions, each taking a single argument.

For example, a function f(a, b) is transformed into f(a)(b).

This is useful for partial application of functions and creating more flexible and reusable components.

An example in Python using a function from the functools module:

from functools import partial

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

# Manual currying
def curried_multiply(x):
    def inner(y):
        return x * y
    return inner

double = curried_multiply(2)
print(double(5))  # Outputs 10

# Using partial for partial application
double_partial = partial(multiply, 2)
print(double_partial(5))  # Outputs 10

Currying helps create specialized functions from general ones, improving readability and code reuse.