-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcurry.py
67 lines (55 loc) · 1.63 KB
/
curry.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"Simple currying for python functions"
import typing
import functools
T = typing.TypeVar("T")
T_func = typing.Callable[..., T]
def curry(func: T_func, *args: list,
**kwargs: dict) -> typing.Union[T_func, T]:
"""
curry python functions
>>> foo = lambda a, b, m: (a+b) * m
>>> curry(foo)(2)()(3)(10)
50
>>> curry(foo)(2)(3, 10)
50
>>> curry(foo)(2, m=10)(3)
50
>>> curry(foo, 2, 3, 10)()
50
>>> curry(print, "baz")(42)
baz 42
>>> curry(lambda: print(42))()
42
curry tries to apply the function with as few arguments as possible,
so try to supply *args and **kwargs together with required arguments
curry also works as a decorator
>>> @curry
... def bar(a, b, m):
... return (a+b) * m
>>> bar(2)()(3)(10)
50
>>> bar(2)(3, 10)
50
>>> bar(2, m=10)(3)
50
>>> bar(2, 3, 10)
50
"""
# invoked on subsequent applications
def _curry(func: T_func, *args: list,
**kwargs: dict) -> typing.Union[T_func, T]:
try:
# test if given arguments suffice
return func(*args, **kwargs)
except TypeError as error:
# don't raise error if too few arguments supplied
msg = error.args[0]
if not "missing" in msg and not "at least" in msg:
raise error
# apply given arguments
return functools.partial(_curry, func, *args, **kwargs)
# don't try to evaluate on first application/decoration
return functools.partial(_curry, func, *args, **kwargs)
if __name__ == "__main__":
import doctest
doctest.testmod()