0

I am experimenting with Functional Programming in Python and I usually end up needing a way to uncurry functions.

I solve this issue by using:

from typing import Callable, TypeVar

T = TypeVar("T")
R = TypeVar("R")

def uncurry(function: Callable[[T], Callable[[T], R] | R]) -> Callable[[T], R]:
    def uncurry_step(*args: T) -> R:
        result = function
        for arg in args:
            result = result(arg)
        return result

    return uncurry_step

Example:

def addition(a: float) -> Callable[[float], float]:
    def inner(b: float) -> float:
        return a + b
    return inner

assert addition(5)(5) == 10
assert uncurry(addition)(5, 5) == 10

Is there a way to replace the user-defined uncurry with something provided within the standard library or a 3rd party like toolz?

Note: This is for educational purposes so performance is not relevant.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736

0 Answers0