Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/currying/currying.py
Original file line number Diff line number Diff line change
@@ -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
27 changes: 27 additions & 0 deletions src/currying/currying_test.py
Original file line number Diff line number Diff line change
@@ -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