Skip to content
On this page

Currying

On this page

Currying

수학과 컴퓨터 사이언스에서, currying은 다중 파라미터를 가진 function을 일련의 단일 파라미터를 가진 함수 여러개로 쪼개는 기법이다.

x = f(a, b, c) 는 다음과 같이 쪼갤 수 있다. h = g(a) i = h(b) x = i(c)

혹은 다음과 같이 나타낼 수 있다. x = g(a)(b)(c)

커링은 함수를 호출하지 않고 단지 반환한다.

설명

const add = (x, y) => x + y;

위 함수를 수학적으로 표현하면 다음과 같다.

f(x, y) => x + y

이 표기법은 다음과 같이 변환할 수 있다.

f(x, y) = g(x)(y) = x + y

이를 자바 스크립트 코드로 변환하면 다음과 같다.

// Normal Function
function add(x) {
return function(y) {
return x + y;
}
}
// Arrow Function
const add = x => y => x + y;

자바 스크립트는 함수가 First-Class Citizen으로 취급되기 때문에 함수를 반환할 수 있다.

이렇게 표현된 add는 다음과 같이 사용할 수 있다.

const addFive = add(5);
addFive(7);

예제

다음 예제는 https://ko.javascript.info/currying-partials를 참조하였다.

시간을 넣어 로그를 출력

const log = (date, importance, message) => console.log(`[${date.getHours()}:${date.getMinutes()}] ${importance}: ${message}`);
const logNow = info => message => log(new Date(), info, message);
const debugNow = message => logNow('DEBUG')(message);
logNow('INFO')('MESSAGE'); // [HH:mm] INFO MESSAGE
debugNow('MESSAGE'); // [HH:mm] DEBUG MESSAGE
from datetime import datetime
def log(date, importance, message):
print(f'[{date.hour}:{date.minute}] {importance}: {message}')
def log_now(info):
def log_message(message):
log(datetime.now(), info, message)
return log_message
def debug_now(message):
log_now('DEBUG')(message)
log_now('INFO')('MESSAGE') # [HH:mm] INFO MESSAGE
log_now('MESSAGE') # [HH:mm] DEBUG MESSAGE

파이썬으로 구현 시 다중 커링을 위와 같이 구현하게 되면 함수 indent가 매우 길어진다.

def test_1(a):
def test_2(b):
def test_3(c):
def test_4(d):
return a + b + c + d
return test_4
return test_3
return test_2
test_1(1)(2)(3)(4) # 10

이를 막기 위해 lambda를 사용하여 익명 함수로 구현하면 다음과 같이 사용할 수 있다.

test_1 = lambda a: lambda b: lambda c: lambda d: a + b + c + d
test_1(1)(2)(3)(4) # 10

LINKS TO THIS PAGE