File tree Expand file tree Collapse file tree 5 files changed +57
-0
lines changed
Expand file tree Collapse file tree 5 files changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+
Original file line number Diff line number Diff line change 1+
Original file line number Diff line number Diff line change 1+ # Curry a given function.
2+ # If the definition uses *args, specify the amount given in a specific case
3+ def curry (f : callable , arity = None ):
4+ if arity is None :
5+ arity = f .__code__ .co_argcount
6+ elif arity < 0 :
7+ raise Exception ("negative arity" )
8+ elif arity < f .__code__ .co_argcount :
9+ raise Exception ("specified arity is lesser than required" )
10+
11+ if arity == 0 :
12+ return lambda : f ()
13+
14+ def inner (* args ):
15+ if len (args ) >= arity :
16+ return f (* args )
17+
18+ return lambda arg : inner (* args , arg )
19+
20+ return lambda arg : inner (arg )
Original file line number Diff line number Diff line change 1+
Original file line number Diff line number Diff line change 1+ from ..src .lib import curry
2+ import pytest
3+
4+
5+ def add_args (* args ):
6+ return sum (args )
7+
8+
9+ def add2 (a , b ):
10+ return a + b
11+
12+
13+ def test_specified ():
14+ assert curry (add_args , 3 )(1 )(2 )(3 ) == 6
15+
16+
17+ def test_negative ():
18+ with pytest .raises (Exception ) as e :
19+ curry (add2 , - 1 )
20+ assert e == "negative arity"
21+
22+
23+ def test_less ():
24+ with pytest .raises (Exception ) as e :
25+ curry (add2 , 1 )
26+ assert e == "specified arity is lesser than required"
27+
28+
29+ def test_unspecified ():
30+ assert curry (add2 )(1 )(2 ) == 3
31+
32+
33+ def test_zero ():
34+ assert curry (add_args , 0 )() == 0
You can’t perform that action at this time.
0 commit comments