diff --git a/src/currying/currying.py b/src/currying/currying.py new file mode 100644 index 0000000..ebfd0e7 --- /dev/null +++ b/src/currying/currying.py @@ -0,0 +1,37 @@ +def curry(func, n): + assert n >= 0, "Error: n can't be negative" + assert isinstance(n, int), "Error: n should be natural number" + if n == 0: + return func + else: + def start(arg): + args = [arg] + if n == 1: + return func(arg) + def continuation(arg): + args.append(arg) + if len(args) == n: + return func(*args) + return continuation + + return continuation + + return start + +def uncurry(curried_func, n): + assert n >= 0, "Error: n can't be negative" + assert isinstance(n, int), "Error: n should be natural number" + + if n == 0: + return curried_func + else: + def uncurried(*args): + assert len(args) == n, f"Error: {n} arguments expected, {len(args)} given" + if n == 1: + return curried_func(args[0]) + result = curried_func + for arg in args: + result = result(arg) + return result + + return uncurried diff --git a/src/currying/currying_test.py b/src/currying/currying_test.py new file mode 100644 index 0000000..dea2968 --- /dev/null +++ b/src/currying/currying_test.py @@ -0,0 +1,27 @@ +from currying import curry, uncurry +import pytest +def summ(a, b): + return a + b + +def test_negative_n_curry(): + with pytest.raises(AssertionError): + curry(summ, -1) + +def test_not_int_n_curry(): + with pytest.raises(AssertionError): + curry(summ, 2.4) + +def test_negative_n_uncurry(): + with pytest.raises(AssertionError): + uncurry(curry(summ, 2), -1) + +def test_not_int_n_uncurry(): + with pytest.raises(AssertionError): + uncurry(curry(summ, 2), 2.4) + +def test_uncurry_wrong_args_count(): + with pytest.raises(AssertionError): + uncurry(curry(summ, 2), 2)(1)(2)(3) + +def test_currying(): + assert curry(summ, 2)(1)(5) == 6