Skip to content

Commit 4bcd0fb

Browse files
committed
Implement currying
1 parent 22f670c commit 4bcd0fb

File tree

5 files changed

+57
-0
lines changed

5 files changed

+57
-0
lines changed

currying/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

currying/src/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

currying/src/lib.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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)

currying/tests/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

currying/tests/test.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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

0 commit comments

Comments
 (0)