Last active
December 14, 2022 16:30
-
-
Save jtraub/c53d27b37e6d625e3dfda3f159b36e64 to your computer and use it in GitHub Desktop.
Implement curry decorator in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from inspect import signature | |
class Applicator: | |
def __init__(self, fn, total_args, args=None): | |
self.fn = fn | |
self.total_args = total_args | |
self.args = [] if args is None else args | |
def __call__(self, *args): | |
concatenated_args = self.args + list(args) | |
if len(concatenated_args) == self.total_args: | |
return self.fn(*concatenated_args) | |
elif len(concatenated_args) > self.total_args: | |
raise TypeError(f"{self.fn.__name__}() takes {self.total_args} positional args but {len(concatenated_args)} were given") | |
return Applicator(self.fn, self.total_args, args=concatenated_args) | |
def curry(func): | |
func_sig = signature(func) | |
number_of_args = len(func_sig.parameters) | |
if 0 <= number_of_args <= 1: | |
return func | |
return Applicator(func, number_of_args) | |
@curry | |
def add(a, b, c): | |
return a + b + c | |
@curry | |
def neg(a): | |
return -a | |
print(neg(10)) # -10 | |
print(add(1)(2)(3)) # 6 | |
print(add(1)(2, 3)) # 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment