함수형 프로그래밍/python
python 으로 curry 만들기
thebirghtwide
2021. 7. 15. 22:45
javascript로 이미 다룬 부분이지만 curry는 아래 함수처럼 동작한다.
def add (a, b)
return a + b
add(1,2)
add(1)(2)
두 개의 변수를 받게 되어 있는 add 함수를 무조건 add( 1, 2) 로 쓰는 것이 아닌 add(1)(2) 로 쓰게 만들어 주는 것이다.
아래는 curry를 실제 구현한 함수와 실행 예제이다.
def curry(func) :
curry.__func_name__ = func.__name__
f_args, f_kwargs = [], {}
def f(*args, **kwargs) :
nonlocal f_args, f_kwargs
if args or kwargs :
print("args", args, "kwargs", kwargs)
f_args += args
f_kwargs.update(kwargs)
return f
else :
print( f_args, f_kwargs)
result = func( *f_args, **f_kwargs)
f_args, f_kwargs = [], {}
return result
return f
def add (a, b) :
return a + b
add2 = curry(add)
print(add2(1)(2)())
# 결과는 3이 나온다.