CodeGym /행동 /Kotlin SELF /fold-wa reduce: sijeom, bin kolekshon, geurigo anjeonhan ...

fold-wa reduce: sijeom, bin kolekshon, geurigo anjeonhan beojeon

Kotlin SELF
레벨 25, 레슨 0
사용 가능

1. Egeuregeisyeon: kolekshon-eseo hana-ui gyeolgwa-ro

Silje peurogeuraem-eul sseugi sijakhago (jageun konsol aepirado) nagayo, geumsae alge doemnida. “mogeul moggyeol”eun jeonbu-ga anigo jeonbu-eui banman haess-eul ppun-imnida. Sayongja (ttoneun jasine)ga wonhaneun geon daebubun gyeolgwa-imnida: jeonche hab, choedae gab, choeso gab, habchin munjayeol, beomju byeol 요약. Jeuk, “modeun jisul-eul boyeojwo”ga anira “jeonche eolmana sseosseuni?” ttoneun “gajang bissan gumae-neun mueosini?”ga doemyeon.

Geureogo yeogi-eseo cho-bojae-ge jaju il-eonaneun “mabeop”i deureonabnida: sarami oebu var sum = 0reul mandeulgo, geu daeum forEach { sum += it }reul sseugo, geureogo nun-eul banchakimyeo munje-reul haegyeolhaessdago saenggakhabnida. Hyeongsikjeogeuro-neun matseubnida. Hajiman seutail-gwa sinroe-seong gwansa-jeon-eseoneun, son-euro mul-eul omgineun geotcheoreom imnida: ongineun geon ganeunhajiman, heullil hwakryul-i nophgo, sogeun ttaemun-e son-i kkeokkeokhaejibnida.

foldwa reduceneun disiprin-eul juseubnida: urin myeonghwakhi Kotlin-ege “yeogi kolekshon-i issgo, yeogi nunkjeok gyuchik-i iss-euni, gyeolgwa-reul dollaejwo”rago malhabnida. Ige egeuregeisyeonimnida: “manyeo elemnteu → hana-ui gyeolgwa”.

Gongshik jeong-ui-neun dan순합니다: fold()wa reduce()neun nunjeok-gwa daeum elemnteu-reul bad-a sae nunjeok gyeolgwa-reul banhwanhaneun yeonsan-eul yeonseokjeogeuro jeogyonghamnida.

2. Aekyumulreiteo: (acc, x) -> saerounAcc eotteohge ilk-eoya hal까

Cheoeum fold(0) { acc, x -> acc + x }reul bomyeon, mabeop gateun neukkim-i deul su issseubnida. Geureohjiman an심하세요: i geon mabeop-i anigo, geunyang aju soljikhan banbokmun-eul 함수로 gajang kkayeoge pyo-hyeonhan geot-il ppun-imnida.

Haengsim idee-neun aekyumulreiteo(bo통 acc라고 부릅니다, accumulator의 약자)입니다. Ige “nunjeok”doeneun gab-euro, han georeumssik 쌓여갑니다. Eoneu sijeom-eseo-na jung-gan gyeolgwa-reul bo-gwanhamnida.

Jeojangham-eul sangsanghaeboseyo. Kolekshon-ui 각 요소-neun dongjeon이고, accneun jeojangham-e imi eolmana deureo issneunji-imnida. Mae dan'gye-eseo han gaji dongjak-eul banbokhabnida: daeum dongjeon-eul gajyeo 와서 hab-eul eopdeiteu 합니다.

Mini do식-euro geuryeobomyeon ireon neukkim-ibnida:

flowchart LR
    A["initial / seutateu"] --> B["acc after 1st element"]
    B --> C["acc after 2nd element"]
    C --> D["acc after 3rd element"]
    D --> E["result"]

fold/reduceui 람다-ui uimi-neun hangsang ttokgatseubnida: “(acc와 x)로부터 다음 acc를 eotteohge mandeulji”.

Tto han 가지 jungyo한 점: 람다는 saeroun aekyumulreiteo gabs-eul banhwanhaeya 합니다. Kotlin-eseoneun 이는 람다 안에서 majimak pyohyeoni 곧 banhwan gabs-euro cheori됨을 uimi합니다 (람다 안에서 return을 sseuneun geon daebubun pilyo eopsseubnida).

foldui “naebu”reul bogo sipdamyeon, munseo-eseo banbokmun-euro geuidae-uro guhyunhan geotcheoreom boineun yese-ga issseubnida: meonjeo accumulator = initial, geurigo 각 요소-e daehae accumulator = combine(accumulator, element), majimak-e accumulatorreul banhwan합니다. Jeuk, i geon mabeop-i anira, geunyang kkayeoge 포장된 for일 ppun입니다.

3. fold: seutateu, bin kolekshon, geurigo junglib elemeonteu

Ije-kkaji maneun kolekshon yeonsan-eun “gyeyak-sang anjeon”haessseubnida: bin liste-eseo filterreul hamyeon bin liste-reul dollyeojugo, countneun 0eul banhwanhamyeo, amudo jeoldae jeompeulhaji 않습니다. folddo i cheolhak-eul 이어갑니다: hangsang jeong-ui-doem—wae냐하면 siijeom gab initiali issgi ttaemun입니다.

Haengsim munjang: fold(initial)eun cheoeum dan'gye-eseo hyeonjae nunjeok gab-i initial라고 ga-jeonghago, geu daeum-e yaso deul-eul “heupsu”hagi sijakhabnida. Ijeom-i reducewa-ui jungyo한 chayiimnida.

Gajang gibon yeseu: su-ui hab

Hab-eun jann-reul ppyodulrineun keullasik-imnida. Geu iyu-neun joeun junglib seutateu, 즉 0ga issgi ttaemun입니다.

fun main() {
    val xs = listOf(1, 2, 3)

    val sum = xs.fold(0) { acc, x -> acc + x }
    println(sum) // 6
}

Saram mal-ro balamyeon: “0-eseo sijakhaeseo, mae xreul acce 더해라”.

Wae foldga bin liste-eseo joeun-ga

Yeogiga foldga jinjja “sium-eul naeswimyeo” pyeonanhaejineun 지점입니다: bin liste-neun drama-reul manddeulji 않습니다. Geunyang “siijeom-e amugeotdo deohaji anh-ass-euni”, gyeolgwa-ga siijeom gab-gwa gatseubnida.

fun main() {
    val empty = emptyList<Int>()

    val sum = empty.fold(0) { acc, x -> acc + x }
    println(sum) // 0
}

Igeun beogeuga 아닙니다. Igeun gyeyak입니다: foldneun hangsang gabs-eul banhwan합니다. Eonje나 initiali issgi ttaemun입니다.

Kolekshon
fold(initial)
Iy유
bin
initial
eopdeiteu dan'gye-ga han beon-do eopsseossda
bin i anin nunjeok gyeolgwa
initial
i 각 요소에서 eopdeiteu-doeeossda

Junglib elemeonteu: wae seutateu-ga uimi-ga iss-eoya hal까

Cho-bojaga fold(0)reul alge doemyeon, wiheomhan saenggak-i saenggimnida: “aha, geureom seutateu-neun hangsang 0-inde?” Geureoge program-i “안정적으로 돌아가는데 틀린” gyeolgwa-reul naeneun gyeong'u-ga saenggimnida. Igeu nopi seunghabnida: 컴파일러는 jomdo mal-eul an hago, erro-do eopsneunde, gyeolgwa-man joreop합니다. Keompyuteo-neun eoreobeor린 geos-eul jeongmal jal gyesanhaebnida—geugeuui gangjeom jung hana-imnida.

Seutateu gabs-ui uimi-neun, dangsin-ui yeonsan-e daehae junglib elemeonteu(ttoneun jeok-eodo 논리적인 출발점)가 되는 것입니다.

Got-eul gyesanhaneun gyeong'u, seutateu-ga 0imyeon gyeolgwa-ga yeongwonhi 0iga doemnida. Waenya하면 0 * mueos-ideun = 0이기 때문입니다. Geureomuro 1eul seontaeghabnida.

fun main() {
    val xs = listOf(2, 3, 4)

    val product = xs.fold(1) { acc, x -> acc * x }
    println(product) // 24
}

Seutateu-neun susja일 pilyo-ga eopsseubnida—jeongmal 괜찮습니다. foldneun dangsin-i siijeom-eul jeonghaneun dae-ro eotteon 타입ido nunjeokhal su issseubnida. Ibeon dan'gye-eseo ihaehaeya 할 중요한 점: initialeun dan순히 gab-man jeonghaneun geosi anira, jaju gyeolgwa-ui 타입eul jeonghagi-do 합니다.

4. reduce: seutateu = cheot beonjjae 요소, geurigo geu hu-ui yeonghyang

reduceneun “fold인데 jom deo jjareun” geotcheoreom boib니다: seutateu gabs-eul an sseodo doenikka요. Geureohgi ttaemun-e reduceneun pyeonrihajiman, dong시에 약간 wiheomhan 도구입니다.

reduceui gyeyak-eun ireon geos입니다: initialeul badji anseubnida. Geureomyeon cheoeum dan'gye-eseo eodieseon'ga cheot accreul gajyeowaya 합니다. Geugeo-reul kolekshon-eseo gajyeo옵니다: cheot beonjjae 요소-ga cheot aekyumulreiteo-ga doem, geurigo yeonsan-eun (cheot beonjjae, du beonjjae) jjak-eseo cheoeum jeogyongdoemnida.

Yeogi-eseo du 가지 silje jeongryeong-i na옵니다: reduceneun bin kolekshon-e jeogyonghal su eopsgo, ttaeroneun reducega “다른 의미”reul nael su issseubnida—dangsin-i cheot 요소-buteo modeun 요소-reul ttokgat-e cheorihaegil gidaehaessdamyeon 말입니다.

reduce-ro hab gyesan (listeuga hwaksilhi bi-eo issji aneul ttae)

fun main() {
    val xs = listOf(1, 2, 3)

    val sum = xs.reduce { acc, x -> acc + x }
    println(sum) // 6
}

Ige ga-neunghan iyu-neun hab-eun 결합법칙(associative)seong-i issgo, “cheot 요소”reul seutateu-ro 삼는 geot-i 논리적이기 때문입니다.

Hamjeong: cheot 요소-ga dareun 요소-deul-cheoreom cheori-doeji anh-assda

Gajang yeonghyang-i keun ye: “du 배-doen 요소-deul-eul habhagija”. foldneun modeun 요소-reul jeongjik하게 du 배 합니다. Hajiman reduceneun geureohji 않습니다. Waenya하면 cheot 요소-ga 갑자기 du 배 doegi jeon-e seutateu accro doeeobeorigi ttaemun입니다.

Bikyohaeboseyo:

fun main() {
    val xs = listOf(5, 2, 10, 4)

    val ok = xs.fold(0) { acc, x -> acc + x * 2 }
    val tricky = xs.reduce { acc, x -> acc + x * 2 }

    println(ok)     // 42
    println(tricky) // 37
}

Wae geureol까?
reduceneun acc = 5ro sijakhago, geu daeum 5 + 2*2 + 10*2 + 4*2reul 수행합니다. Cheot 5neun du 배 doeeoji anh-assseubnida. Waenya하면 geugeo-neun “일반 규칙”eul geochineun 과정 자체가 eops-eossgo, geunyang seutateu-ro doeeossgi 때문입니다.

Igeun “Kotlin-i dongsag-eul chideun geot”i anigo, reduce gyeyak-ui jikjeopjeogin gyeolgwa입니다.

Gajang jungyohan wiheom: bin kolekshon

reduceneun seutateu-reul cheot 요소-eseo gajyeo오기 ttaemun-e, bin kolekshon-eseoneun geuge bulganeung합니다. Geureomuro reducereul bin kolekshon-e seumyeon 예외를 던집니다 (즉, cheori하지 않으면 peurogeuraem-i jungdan doemnida).

5. Anjeonhan beojeon-deul-gwa jeonghwakhan seontaek

데이터가 eops-eul su issdamyeon, ol바른 모델-eun “listeuga bi-eo issji anhagil barandae”ga anira “데이터가 eops-eumyeon, gyeolgwa-do eopsda”입니다. Kotlin-eun yeogi-eseo dangsin-eul 달래지 않습니다: anjeonhan gyeyak-eun nullable 타입-euro pyo현됩니다.

reduceOrNull: gyeolgwa-ga eops-eul su issda

reduceOrNull { ... }eun jinjja ro geureohge haeb니다: kolekshon-i bimyeon nulleul banhwan하고, bi-ji aneumyeon reducecheoreom dongjak합니다.

fun main() {
    val empty = emptyList<Int>()

    val sum = empty.fold(0) { acc, x -> acc + x }
    val reduced = empty.reduceOrNull { acc, x -> acc + x }

    println(sum)     // 0
    println(reduced) // null
}

Uimi-ro beonyeokhaemyeon:

  • foldneun “데이터가 eops-eodo (seutateu ttaemun-e) gyeolgwa-neun hangsang issda”라고 말합니다.
  • reduceOrNullneun “데이터가 eops-eumyeon—gyeolgwa-do eopsda”라고 말합니다.

Dul da jeongsangjeogin seontaek입니다. Eotteon geos-eul 고를지-neun munje-ui uimi-e ttara 달라집니다. Hab-eul 구할 때는 “0”ga 편리한 gyeong'u-ga 많습니다. 0neun “amugeotdo eops-eossda”reul uimihal su issgi 때문입니다. Hajiman “choeso gumae” 같은 geos-eoseo 0neun 거짓일 su issseubnida. 0 USDT gumae-neun halin 행사라도 suseureoun 일이니까요.

Silje jeongryeong: seontaek gyuchik

Yeonsan-e jaeyeonseong 있는 junglib seutateu-ga issdamyeon (hab → 0, got → 1, munjayeol → "", listeu → emptyList() deung), foldga daebubun deo jal ilkeo-jigo 신뢰롭게 동작합니다: bin 데이터-eseo-do jeong-ui-doe니까요.

Seutateu-ro “cheot 요소”ga 논리적이고, peurogeuraem uimi-sang kolekshon-i bi-ji aneul geot-eul 보장handamyeon, reducereul sseodo doemnida.

Hajiman geu bojang-i jogeum-irado heull릴 su issdamyeon (sayongja 입력, filter, geomsag), cheoeum-buteo reduceOrNulllo jeonhwanhae, gyeyak-eul jeongjik하고 anjeonhage mandeuneun 게 좋습니다.

6. Konsol aep yeseu: chonggye-reul gyesanhaebogi

Ije uri-neun jeongjeok하게 fold/reduceOrNullreul, kolekshon-gwa keommandeu pyeon-eseo baljeon-sikyeoon “silje” konsol aep-e jeogyonghaebogessseubnida. Mobeul daesi: urien yeonsan (ye: 지출) listeuga issgo, OOP eopsi geunyang Pair<String, Int> ssang-euro bogwanhamnida. 여기에 firstneun beomju, secondneun geumaek입니다.

Jungyo: yeogi-eseo-neun saeroun keommandeureul chugahaji도 않고, aekitegcheo-reul jitsji도 않습니다. Dan지, silje 코드에서 “son-euro haneun suhak”eul ilki swip-ge aggeuregeisyeon 함수 로 ppaeneun beop-man boyeojum니다.

Ilikim-eul wihan 타입 (ajik klaseu eopsi)

typealias Entry = Pair<String, Int>

Ne, ajikdo Pairimnida. Hajiman 이제 코드-e seo jab-eum-i jul-eossseubnida: List<Entry>neun List<Pair<String, Int>>보다 훨씬 gajaenghi ilkim swip습니다.

Chonghab-eul fold(0)ro

typealias Entry = Pair<String, Int>

fun totalAmount(entries: List<Entry>): Int =
    entries.fold(0) { acc, (_, amount) -> acc + amount }

fun main() {
    val entries = listOf("food" to 120, "taxi" to 250)
    println(totalAmount(entries)) // 370
}

Joheun jeom: entriesga bimmyeon, totalAmountneun geuraedo jeonghwakhi 0eul banhwan합니다. if (entries.isEmpty()) ... 같은 geot-eul deokji 않아도 됩니다.

Gajang keun yeonsan-eul reduceOrNull로

Ije deo heungmi로운 yeseu입니다: geumaek-i choedae인 엔트리-reul chatgi. Yeogi-eseo seutateu “0”neun matji 않습니다. Bin listeu일 때 jonjaehaji 않는 엔트리-reul jib-eo넣go sipji 않기 때문입니다. Geureomuro “gyeolgwa-ga eops-eul su issda”라는 gyeyak-i jeongjik합니다.

typealias Entry = Pair<String, Int>

fun maxEntryOrNull(entries: List<Entry>): Entry? =
    entries.reduceOrNull { acc, x ->
        if (x.second >= acc.second) x else acc
    }

fun main() {
    val entries = listOf("food" to 120, "taxi" to 250, "food" to 80)

    val max = maxEntryOrNull(entries)
    println(max) // (taxi, 250)
}

null-eul noneuji anko gyeolgwa-reul 출력하는 beop

typealias Entry = Pair<String, Int>

fun maxEntryOrNull(entries: List<Entry>): Entry? =
    entries.reduceOrNull { acc, x -> if (x.second >= acc.second) x else acc }

fun main() {
    val entries = emptyList<Entry>()

    val max = maxEntryOrNull(entries)
    println(max?.second ?: 0) // 0
}

Yeogi-eseo urin “choedae gumae-ga 0이다”라고 danjeonghaji 않습니다. Dan지 “choedae-ga eops-eumyeon—출력용으로 0으로 boyeojugessda”라고 말합니다.

Igeu mi묘하지만 jungyohan chayi입니다: 함수 naebu gyeyak-eun jeongjik하고, 출력 포맷팅-eun daleun uigyeoljeong입니다.

7. fold와 reduce 사용 시 jaju natananeun silsu

Silsu #1: listeuga bi-eul su issneunde reducereul sseuneun geot.
Igeu daebubun “사람이 나빠서”ga 아니라, filter-reul sseun 뒤에 filter-ga modeun geos-eul beory릴 su issdaneun geot-eul 잊어서 생깁니다. Gyeolgwa-neun heos-eopsi teojineun crash입니다. 습관은 dan순합니다: bi-ji aneum-eul cheoljeohi 보장hal su eopsdamyeon, fold(jeong상이 되는 initiali iss-eul ttae) ttoneun reduceOrNull(gyeolgwa-ga eops-eul su iss-eul ttae)을 seontaek하세요.

Silsu #2: 잘못된 initialeul seontaekhae “안정적으로 틀린” gyeolgwa-reul 얻는 geot.
Hab-e fold(0)—완벽합니다. Got-e fold(0)—100% 0입니다. Minimum-e fold(Int.MAX_VALUE)—tte론 동작하지만, mabeop-ui susja처럼 보이고, 타입이나 데이터 범위를 바꾸면 깨질 수 있습니다. Seutateu gabs-ui uimi-neun always seolmyeonghaeya 합니다: geugeo-ga mueos-eul uimi하며, wae gyeolgwa-reul 왜곡하지 않는지.

Silsu #3: reducereul “ttokgat-e, dan지 jjareuge”라고 saenggak하고 cheot 요소-reul nolliji 않는 geot.
Hamjeong-eun “du 배 합” 같은 munje-eseo deureonabnida: reduceeseo cheot 요소-neun seutateu가 되어, dangsin-ui cheori 규칙-eul geochiji 않습니다. fold와 reducee ttokgat-eun 람다-reul 넣어도, seutateu gyeyak-e tta라 gyeolgwa-ga 달라질 수 있습니다.

Silsu #4: 람다 매개변수 yeokhal-eul heundeul-eoseo gyuchik-eul “geokkuro” sseuneun geot.
fold/reduceeseo cheot beonjjae 매개변수-neun nunjeok gab (acc), du beonjjae-neun daeum 요소 (x)입니다. Ireohge name-eul dadeul jyeotda-ga (a, b, c) cheoreom jiseonghae beorimyeon, du세 번째 줄만 ga도 두뇌가 헷갈리기 sijakhabnida. acc와 x(ttoneun acc와 item)라는 dan순한 i-reum disiprin-i beogeureul 실질적으로 줄여줍니다.

Silsu #5: egeuregeisyeon 람다를 30줄짜리 mini soseol-lo mandeuneun geot.
Gisuljeogeuro-neun 가능하지만, ilki himdeul seubnida. Nunjeok 안에 복잡한 로직이 생기면, 람다 안에서 jageun 로컬 valeul sseugeona, 계산 일부를 별도 함수로 bbaeneun 게 좋습니다. fold/reduce(acc, x) -> saerounAccman 남겨두세요. Joheun gijeon-eun: i geon bonjiljeogeuro 짧은 loop입니다. 로직은 “loop 크기”여야지 “졸업논문 크기”가 아니어야 합니다.

1
과제
Kotlin SELF, 레벨 25, 레슨 0
잠금
최종 점수
최종 점수
1
과제
Kotlin SELF, 레벨 25, 레슨 0
잠금
장바구니
장바구니
1
과제
Kotlin SELF, 레벨 25, 레슨 0
잠금
두 배로 합산
두 배로 합산
1
과제
Kotlin SELF, 레벨 25, 레슨 0
잠금
최고 기온
최고 기온
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION