1. Aggregation-gwa foldreul “ilbanjeok technique”uro bogi
Programming-eul cheoeum sijakhals ttaen geuui modeun munjega geu gyeolro seollyeongdoen cheoreom boimnida: “loop-eul sseugo, var result mandeulgo, loop aneseo accumulatehanda.” Geurigo igeun majseumnida… hajiman geureon loop-ga manhajimyeon, eodiseo mueoseul accumulatehaneunji, wae eoneu sungan “udeonaege” reuse doeeosseuneunji heundeullyeo jinnaegie swiwopseumnida.
Aggregation-eun “many elements → one final result”reul wihan technique-e daehae deo jeongjehan ireumipnida. Geu final result-neun sum, minimum, report string, category-by-category accumulation dictionary, mueos-ideun doel su itseumnida. Jungyohan geon uri-ga mueoseul gyesanhaneunya-ga anira, geugeol eotteoke saenggakhaneunyapnida: accumulator (intermediate result)ga itgo, daeum element-reul mannasseul ttae geu accumulator-reul eotteoke updatehalji gyuchik-i it습니다.
foldreul universal “result constructor”ro bogi
Du mal-ro jeongrihamyeon, foldneun “collection-eul iteratehaneunde, final result type-eul jiksjeop jeonguihaneun” bangbeopipnida. Geurigo final result type (R)neun element type (T)wa jeonhyeo gatji anado doemnida. Ige kkeutnaeju-neun core idea-imnida: uri-neun geunyang “number-reul deohanda”ga anira, “pilyohan formae matneun result-reul assemblehanda”reul haneun geosipnida.
Contract gwangyeom-e seo foldneun start value-wa combiner function-eul badseumnida. I function-eun mae beon old accumulator-wa new element-reul bada new accumulator-reul returnhamnida. Documentation-eul geurae dereul boado “accumulated + element → new accumulated”ro igi han jul-euro ilg힐 su itseumnida.
“black box”cheoreom saenggakhaji anke schemata-ro bopsida:
flowchart TD
A["initial (acc)"] --> B["combine(acc, x1) -> acc1"]
B --> C["combine(acc1, x2) -> acc2"]
C --> D["combine(acc2, x3) -> acc3"]
D --> E["... итоговый accN"]
Loop-e ge 익숙하다면 ireoke saenggakhals su itseumnida: foldneun “culture-issneun loop”imyeo, 바깥의 var dae신 “always return the next accumulator”reul gangjehamnida.
Neutral element-gwa initial seontaek
fold(initial) { acc, x -> ... }eseo initial parameter-neun “geunyang starthaneun eotteon su”ga anira, operation meaning-e part-imnida. Igeul jaju neutral element-rago bureuneunde, geu tteut-eun “result-reul 망가뜨리지 않는” start value-raneun geosipnida.
Sum-eul gyesanhanda면 neutral element-neun 0ipnida. 0 + x = x 이기 때문입니다. Product-reul gyesanhanda면 1ipnida. 1 * x = x 이기 때문입니다. String-eul assemblehanda면 neutral element-neun bo통 빈 문자열 "" 또는 StringBuilder() (approach-e 따라)ipnida. Mapeul assemblehanda면 neutral element-neun empty map-imnida.
아래는 “자주 쓰는 aggregate → 좋은 initial” mini table입니다:
| 무엇을 모으나 | 결과 타입 | initial | 이유 |
|---|---|---|---|
| 합계 | |
|
0은 합에 영향을 주지 않음 |
| 곱 | |
|
1은 곱에 영향을 주지 않음 |
| 텍스트 연결 | |
|
빈 문자열은 문자를 추가하지 않음 |
| 긴 텍스트 | |
|
객체를 “계속 덧붙여” 완성함 |
| 키별 누적 | |
|
빈 구조에서 시작함 |
가장 불쾌한 점은, 잘못된 initial이 컴파일 오류로 이어지지 않는 경우가 많다는 것입니다. 프로그램은 “돌아가지만”, 결과는 헛소리를 뱉습니다. 이건 크래시가 아니라 조용히 당신을 비웃는 버그입니다.
2. Expense 예제로 보는 기본 aggregation
예제가 “진공 속의 구형 숫자”가 되지 않도록, expense tracking 콘솔 프로젝트를 계속 이어가겠습니다. 아직 OOP 없이: expense는 Pair<String, Int>이고, first는 category, second는 (가상의) 금액입니다.
먼저 간단한 데이터셋부터 시작하겠습니다:
fun main() {
val expenses: List<Pair<String, Int>> = listOf(
"food" to 120,
"taxi" to 250,
"food" to 80,
"books" to 540
)
println(expenses)
// [(food, 120), (taxi, 250), (food, 80), (books, 540)]
}
fold로 구하는 총합
이제 전체 expense의 총합을 계산해봅시다. 전형적인 “many numbers → one number” 케이스입니다:
fun main() {
val expenses = listOf(
"food" to 120,
"taxi" to 250,
"food" to 80,
"books" to 540
)
val total = expenses.fold(0) { acc, (_, amount) ->
acc + amount
}
println("Total: $total") // Total: 990
}
작은 디테일에 주목하세요: pair를 (_, amount)로 destructuring 합니다. category는 합계에 필요 없으므로, _는 “이건 무시한다”는 정직한 신호입니다.
혹시 “그럼 왜 sumOf를 안 쓰죠?”라는 생각이 들었다면, 아주 타당합니다. 하지만 오늘은 의도적으로 fold 패턴을 훈련합니다: “예쁘게 해주는” 준비된 함수가 없을 때 도움이 되기 때문입니다.
fold로 조건부 count 만들기
Kotlin에는 count { ... }가 있고, 실전에서는 그걸 쓰게 됩니다. 하지만 fold를 제대로 이해하려면, 한 번쯤 count를 “손으로” 만들어보는 게 좋습니다. 그래야 “aggregation”이 돈의 합만이 아니라 “사실의 합”일 수도 있음을 체감합니다.
예: 200보다 큰 expense는 몇 개인가?
fun main() {
val expenses = listOf(
"food" to 120,
"taxi" to 250,
"food" to 80,
"books" to 540
)
val bigCount = expenses.fold(0) { acc, (_, amount) ->
if (amount > 200) acc + 1 else acc
}
println("Big expenses: $bigCount") // Big expenses: 2
}
여기서 accumulator는 단순히 “지금까지 몇 개를 찾았는지”를 나타내는 숫자입니다. 조건을 만족하는 element를 만나면 1 증가시킵니다.
3. Minimum과 maximum도 aggregation이다
Minimum/maximum은 초보자가 자주 두 가지 길로 가는 전형적인 문제입니다: 리스트를 sort 한다(비싸고 불필요함)거나, var min = ... 같은 loop를 쓰다가 “리스트가 비어 있으면 어떻게 하지?”라는 문제를 만나게 됩니다.
오늘은 empty case까지 바로 고려하는 실용적인 “fold 스타일” minimum을 봅니다. 아이디어는 간단합니다: accumulator를 nullable로 만듭니다.
예: minimum expense amount를 찾기
fun main() {
val expenses = listOf(
"food" to 120,
"taxi" to 250,
"food" to 80,
"books" to 540
)
val minAmount: Int? = expenses.fold(null as Int?) { acc, (_, amount) ->
if (acc == null || amount < acc) amount else acc
}
println("Min amount: $minAmount") // Min amount: 80
}
이 접근의 장점은 empty list에도 올바르게 동작한다는 점입니다:
fun main() {
val empty = emptyList<Pair<String, Int>>()
val minAmount: Int? = empty.fold(null as Int?) { acc, (_, amount) ->
if (acc == null || amount < acc) amount else acc
}
println("Min amount: $minAmount") // Min amount: null
}
즉, “데이터가 없으면 결과도 없다”를 정직하게 표현하는 것입니다. “데이터가 없으면 minimum을 10억으로 하자” 같은 방식보다 낫습니다. 그런 10억은 나중에 슬쩍 report에 섞여 들어가 “정상 결과”처럼 행동하곤 합니다.
4. fold와 StringBuilder로 텍스트 assemble하기
콘솔 프로그램을 만들다 보면 언젠가 “성인용 앱처럼” 출력하고 싶어집니다: 여러 줄, 정렬, 깔끔한 합계. 그런데 여기서 +로 끝없는 string concatenation을 하다 보면 코드가 스파게티가 되기 쉽습니다.
fold는 report를 assemble하는 데 아주 잘 맞고, 특히 accumulator를 StringBuilder로 두면 좋습니다. 이 경우 final result는 숫자가 아니라 텍스트입니다.
가장 단순한 report를 만들어봅시다: 구매 1건 = 1줄.
fun main() {
val expenses = listOf(
"food" to 120,
"taxi" to 250,
"food" to 80
)
val report = expenses.fold(StringBuilder()) { acc, (category, amount) ->
acc.append(category)
.append(": ")
.append(amount)
.append('\n')
}.toString()
print(report)
// food: 120
// taxi: 250
// food: 80
}
“트릭”에 주목하세요: lambda는 StringBuilder를 반환합니다. append는 같은 객체를 반환하므로, acc.append(...).append(...)는 여전히 같은 accumulator입니다. 우리는 단지 객체를 “자라게” 만드는 것입니다.
이제 report에 total line을 추가해봅시다. 여기서는 two-step approach가 깔끔합니다: sum은 따로 계산하고, text format도 따로 만듭니다. 이렇게 하면 코드가 더 읽기 쉽습니다.
fun main() {
val expenses = listOf(
"food" to 120,
"taxi" to 250,
"food" to 80
)
val total = expenses.fold(0) { acc, (_, amount) -> acc + amount }
val report = expenses.fold(StringBuilder()) { acc, (category, amount) ->
acc.append("- ")
.append(category)
.append(": ")
.append(amount)
.append('\n')
}.append("Total: ").append(total).append('\n')
.toString()
print(report)
// - food: 120
// - taxi: 250
// - food: 80
// Total: 450
}
물론 한 번의 fold로 전부 할 수도 있지만, 그러면 lambda 안에 “side computation”이 끼어들어 유지보수가 어려워집니다. 학습 단계에서는 계산과 formatting을 분리하는 편이 낫습니다. 뇌도 깔끔한 architecture를 좋아합니다.
5. Structure assemble와 aggregation 조합
Map으로 category별 합계 누적하기
이제 핵심입니다: fold는 “숫자 1개”나 “텍스트 1개”뿐 아니라, 전체 structure도 assemble할 수 있습니다. Expense tracking에서는 “category → category sum”이 정말 자주 필요합니다.
우리는 Map<String, Int>를 얻고 싶습니다:
- "food" -> 200
- "taxi" -> 250
- "books" -> 540
이를 fold로 만들되, accumulator는 MutableMap<String, Int>로 둡니다.
fun main() {
val expenses = listOf(
"food" to 120,
"taxi" to 250,
"food" to 80,
"books" to 540
)
val totalsByCategory: Map<String, Int> =
expenses.fold(mutableMapOf<String, Int>()) { acc, (category, amount) ->
acc[category] = (acc[category] ?: 0) + amount
acc
}
println(totalsByCategory) // {food=200, taxi=250, books=540}
}
여기서 중요한 포인트는, 왜 마지막에 acc를 반환하느냐입니다. fold의 lambda는 “다음 accumulator 값”을 반드시 반환해야 합니다. 우리는 acc를 변경했지만 (mutable object라서), fold는 다음 step에 넘길 반환값을 여전히 기대합니다. 그래서 패턴은 이렇게 됩니다: “acc 업데이트 → acc 반환”.
처음엔 “map을 이미 바꿨는데 왜 반환까지?”가 이상하게 느껴질 수 있습니다. 이유는 간단합니다: fold는 immutable이든 mutable이든 동일하게 동작하도록 설계되어 있고, contract는 항상 “새 accumulator를 반환하라”이기 때문입니다.
Structure에서 final result로: “가장 비싼 category”
이미 “category → sum” map이 있다고 가정해봅시다:
val totalsByCategory = mapOf(
"food" to 200,
"taxi" to 250,
"books" to 540
)
이제 “어떤 category가 가장 비싼가”를 알고 결과를 출력하고 싶다고 합시다. empty case까지 깔끔하게 처리하면서 fold로 풀어보겠습니다.
fun main() {
val totalsByCategory = mapOf(
"food" to 200,
"taxi" to 250,
"books" to 540
)
val best: Pair<String, Int>? =
totalsByCategory.entries.fold(null as Pair<String, Int>?) { acc, e ->
val current = e.key to e.value
if (acc == null || current.second > acc.second) current else acc
}
println(best) // (books, 540)
}
여기서는 key와 value가 모두 필요하므로 entries를 aggregate합니다. accumulator에는 Pair<String, Int>, 즉 “현재까지 찾은 최고 pair”를 넣습니다.
Refactoring: “main 안의 magic” 대신 aggregator function
Aggregation이 1~2개를 넘어서면 main이 금방 “부엌”처럼 됩니다: 코드를 굽고, 로직을 끓이고, 누군가는 report를 찍으려 하고… 그래서 aggregator를 function으로 빼겠습니다. 이렇게 하면 프로그램이 더 읽기 쉬워지고 “코드는 function 안에 산다, main에 몰아넣지 않는다”는 습관이 생깁니다.
세 가지 function을 만들겠습니다:
- totalAmount(expenses) — 전체 합계
- minAmountOrNull(expenses) — minimum amount (없으면 null)
- totalsByCategory(expenses) — category별 합계 map
fun totalAmount(expenses: List<Pair<String, Int>>): Int =
expenses.fold(0) { acc, (_, amount) -> acc + amount }
fun minAmountOrNull(expenses: List<Pair<String, Int>>): Int? =
expenses.fold(null as Int?) { acc, (_, amount) ->
if (acc == null || amount < acc) amount else acc
}
fun totalsByCategory(expenses: List<Pair<String, Int>>): Map<String, Int> =
expenses.fold(mutableMapOf<String, Int>()) { acc, (category, amount) ->
acc[category] = (acc[category] ?: 0) + amount
acc
}
이제 main은 훨씬 차분해집니다:
fun main() {
val expenses = listOf(
"food" to 120,
"taxi" to 250,
"food" to 80,
"books" to 540
)
val total = totalAmount(expenses)
val min = minAmountOrNull(expenses)
val byCategory = totalsByCategory(expenses)
println("Total: $total") // Total: 990
println("Min expense: $min") // Min expense: 80
println("By category: $byCategory") // By category: {food=200, taxi=250, books=540}
}
이 스타일은 실수 확률도 낮춥니다: 각 aggregator를 작은 데이터셋으로 따로 테스트할 수 있어서, 로직 버그를 더 빨리 잡을 수 있습니다.
6. fold를 패턴으로 쓸 때 흔한 실수
실수 1: 잘못된 initial (neutral element).
정말 흔한 상황입니다: product를 구하려고 했는데 fold(0) { acc, x -> acc * x }라고 써서, 항상 0이 나옵니다. 컴파일러는 안 혼내고, 프로그램은 돌아가지만, 결과는 100% 틀립니다. 습관을 들이세요: “element가 하나도 없으면 결과는 무엇이어야 하는가?”를 먼저 말해보고, 그에 맞춰 initial을 고르세요.
실수 2: “MutableMap을 바꾸긴 했는데 acc 반환을 잊음”.
fold 안에서 mutable structure를 accumulator로 쓰더라도, lambda는 반드시 무언가를 return해야 합니다. 초보자는 map update를 해놓고 마지막 줄에 실수로 acc[category] = ... 같은 expression을 남겨두곤 합니다. 그러면 lambda가 map이 아니라 Int?를 반환하게 되어 타입이 깨집니다. 규칙은 단순합니다: mutable accumulator라면 lambda 끝에 명시적으로 acc를 쓰세요.
실수 3: empty list를 의식하지 않고 fold(Int.MAX_VALUE)로 “minimum”을 만들려 함.
list가 비어 있지 않을 때는 돌아갑니다. 하지만 empty list가 되는 순간, Int.MAX_VALUE를 “minimum”으로 내보내고, 그 값이 report에서 정상 결과처럼 살아남습니다. accumulator를 nullable로 두고 데이터가 없으면 null을 반환하는 편이 훨씬 정직합니다. 또는 ...OrNull 같은 안전한 contract를 쓰세요. empty result는 중요한 정보입니다.
실수 4: fold lambda가 너무 복잡해져서 한 번에 모든 걸 하려 함.
fold는 강력해서 “계산도 하고, filter도 하고, format도 하고, 파일 저장까지” 같은 유혹이 생깁니다. 그러면 lambda 하나 안에 mini-program이 들어갑니다. lambda가 비대해지는 게 보이면 멈추고, 조각을 function으로 빼거나 최소한 lambda 내부의 local val로 분리하세요. fold는 명확함을 좋아합니다: (acc, x) -> newAcc, one-man show 없이.
실수 5: acc와 x 역할을 헷갈림(로직이 “뒤집힘”).
가끔 acc를 acc와 비교하거나, x를 x에 더하는 등 “뭔가 이상한” 코드가 됩니다. 이름 규율이 실제로 도움이 됩니다: 역할이 보이도록 파라미터를 명명하세요: acc와 expense, acc와 amount, best와 candidate. 그리고 pair destructuring을 파라미터에서 바로 하는 것도 주저하지 마세요. 인지 부하를 줄여줍니다.
GO TO FULL VERSION