Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
커링은 단일 호출로 처리하는 함수를 각각의 인수가 호출 가능한 프로세스로 호출된 후 병합되도록 변환하는 것이다.
커링을 사용하면, 함수를 만들면서 일부 인자만 먼저 고정하고 나중에 나머지 인자를 적용할 수 있다. 이를 통해 재사용성이 높은 작은 함수를 만들 수 있고, 같은 로직을 여러 상황에 맞춰 쉽게 변형할 수 있다.
여러 개의 작은 함수들을 커링을 통해 결합하면, 더욱 선언적이고 모듈화된 코드 구성이 가능해진다.
구현의 사고 과정
먼저 currying을 지원하는 함수인 curry는 함수를 인자로 받아야한다.
curry라는 인자를 전달 받아 그 인자로 호출하는 함수를 반환해야한다.
이렇게 하면 커링의 정의에서 이야기한
단일 호출로 처리하는 함수를 처리할 수 있다.이제 전달 받는 인자의 개수를 고려하여 조건문으로 분기한다.
조건문은 curry로 전달하는 함수(fn)의 인자 수와 커링되는 함수(curried)의 인자 수를 비교하여
전달한 인자보다 개수가 같거나 많다면, curry로 전달하는 함수(fn)을 그대로 호출하고,
전달한 인자보다 개수가 적다면 curried 함수를 재귀 호출하는 함수를 반환한다.
예를 들면, fn이
라면, sum(1, 2, 3)으로 호출 했을 때나 sum(1, 2, 3, 4)로 호출 했을 때가 전달한 인자보다 개수가 같거나 많은 경우이고,
sum(1)(2, 3), sum(1, 2)(3)으로 호출 했을 때가 전달한 인자보다 개수가 적을 때이다.
그러므로, curried를 재귀 호출하는 함수는 새로운 인자(위의 예시에서 2, 3이나 3)를 받아야하고 rest parameter 문법을 이용하여 curried 함수는 재귀 호출 될 때, 처음 호출 됐을 때의 인자와 새로 전달하는 인자를 전달해 호출한다.