We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Curry

Number: 2740

Difficulty: Medium

Paid? Yes

Companies: N/A


Problem Description

Given a function fn, implement a curry function that returns a curried version of fn. The curried function gathers arguments over multiple calls (e.g. fn(a)(b)(c), fn(a, b)(c), fn()(a, b, c)) until the total number of provided parameters reaches the original function’s arity, at which point it invokes fn and returns its result.


Key Insights

  • The curried function must handle accumulations of arguments across multiple invocations.
  • The function checks if the number of collected arguments is equal to or exceeds fn's parameter count.
  • Once enough arguments have been collected (fn.length), fn is invoked with them.
  • The solution must work even if arguments are provided in groups or with empty calls.

Space and Time Complexity

Time Complexity: O(n), where n is the number of arguments processed, as each call simply aggregates arguments.
Space Complexity: O(n), to store the cumulative arguments across invocations.


Solution

We implement a closure that accumulates provided arguments. Each time the returned function is called, it aggregates new arguments with those from previous calls. When the total number of arguments reaches the original function's arity, we invoke fn with these arguments. This is achieved by defining an inner function that captures the accumulated arguments in its closure. The main idea is to check the number of collected arguments and either return a new function waiting for more arguments or return the final computed result by calling fn.


Code Solutions

def curry(fn):
    # The curried function that accumulates arguments
    def curried(*args):
        # If enough arguments have been collected, call the original function
        if len(args) >= fn.__code__.co_argcount:
            return fn(*args)
        # Otherwise, return a function to collect more arguments
        def next_func(*more_args):
            return curried(*(args + more_args))
        return next_func
    return curried

# Example usage:
def sum(a, b, c):
    return a + b + c

curried_sum = curry(sum)
print(curried_sum(1)(2)(3))  # Outputs 6
← Back to All Questions