CodeGym /행동 /Kotlin SELF /Sequence: lazy seong-gyeok-gwa terminal yeonsan

Sequence: lazy seong-gyeok-gwa terminal yeonsan

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

1. wae Sequencega piryo hal-kka?

filter → map → filter → map chein-eul sseugi sijakhamiyeon, kodeuga “saram-ui saenggak” gateun hyeongtaero gakkawojineun joteun neukkim-i deumnida: “jichul-eul gajigo, piryo han geotman namgigo, byeonhwanhago, gyesanhaera”. Hajiman ilban keollekshyeon-eseo-ui chein-eneun sumgyeojin myeon-i itsseumnida: manh-eun dan-gye-ga jung-gan keollekshyeon-eul “jigeum i sungan” saengseonghamnida. Jageun deiteo-eseoneun jeonhyeo munjega an doejiman, keun deiteo-eseoneun bulpiryo han il-gwa bulpiryo han memory-ro ieojil su itsseumnida. Balo yeogi-eseo Sequencega deungjanghamnida. Sequencereul sayonghamyeon yeonsan-eul yocheong-doel ttae—jeongmal-ro gyeolgwa-reul yocheonghaess-eul ttae—pilyohan mankeumman gyesan하도록 chein-eul seolmyeonghal su itsseumnida.

Jungyohan jeom: Sequenceneun “gijeok-ui gwasok button”i anira dareun silhaeng modelimnida. Oneul-ui mokpyo-neun chein-i eonje jeongmal silhaengdoeneunji, geurigo wae gakkeum “amugeotdo an haessneunde?”cheoreom 느껴지는ji ihaehaneun geosimnida.

Sequenceran? geurigo eotteohge eodneun-ga?

Keollekshyeon Listga wansseongdoen pasuta jeopsi-ra면 (baro meogeul su 있고, myeot gaeinji sael su 있고, jeongryeolhal su 있고, chinguwa “ijeo-geo an jeongryeoldoeeossne”라고 ttaegil su itdamyeon), Sequenceneun deo gakkaun geosi “resep-i”imnida: “jaeryo-reul gajyeo-ogo, geoleonaego, jareugo, bokkeo…”. Resep-man-euro neun baeg-i buleujji anhseumnida. Baeg-eul buleuge 하는 geos-eun jori-reul sijakhan sunganimnida.

Kotlin gwanjeom-eseo Sequence<T>neun banbokhal su inneun (즉 Iteratorreul tonghae 순회 가능한) inteopeiseu-imnida. Ttareoseo Sequenceneun “oenjjok-eseo oreunjjok-euro han beon ssak dora-gan-da”haneun yongdo-eneun jal matjiman, indekseu-ro-ui im-ui jeopgeun (random access) eun yaksolhaji anhseumnida (List-ga 아닙니다).

Oneul-ui haengbokhan hagseub gyuchik-eun ireohseumnida:

Sequenceneun lazyhaseumnida: jung-gan dan-gye-neun baro silhaengdoeji anhseumnida. Geudeul-eun terminal yeonsan-i natana서 gyeolgwa-reul yocheonghal ttae-man silhaengdoemnida.

asSequence()ro keollekshyeon-eul lazy modeuro jeonhwanhagi

Keollekshyeon-i issgo, geu-e lazy silhaeng model-eul jeog-yonghago sipdamyeon, 보통 ireohge 합니다:

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

    val ys = xs.asSequence()
        .filter { it % 2 == 0 }
        .map { it * 10 }
        .toList()

    println(ys) // [20, 40]
}

Kkeut-e itneun toList()reul jujjae-ro bosaeyo: igeun “koseumethik”i anira, “OK, Kotlin, ije jeongmal gyesanhaeseo ilban list-ro jwo”라고 malhaneun sungan-imnida.

Kotlin munseo-wa 예제-eseo-do daebubun baro i paeteon-eul 보여줍니다: Sequence chain-eul mandeulgo, kkeun-e toList()ro 최종 keollekshyeon-eul eodneun geot.

3. jung-gan yeonsan-gwa terminal yeonsan

Jigeum-buteo-neun 디버깅 sigan-eul achuie jeoldaero 아끼고, sin-gyeong se포 du-se gae jeongdo (peurogeuraemeo-ui sin-gyeong se포-neun 아시다시피 immutable)reul guhae-juneun jungyohan saeng-gak-eul hagessseumnida.

Jung-gan yeonsaneun, gyeogsang-eun da-si Sequencereul banhwanhayeo “pipeline”eul gyesok gusunghaneun yeonsan-imnida: map, filter, distinct, sorted (ne, sequence-edo byeol-do-ui beori-eonteu-ga itsseumnida), take, drop deung manh-eun geotdeul. I yeonsan-deul-eun jigeum 당장 gyesan-eul haeya hal 의무-ga eopsseumnida—geudeul-eun danji “pipeline-e dan-gye han gae”reul deohaneun geotppun-imnida.

Terminal yeonsaneun gyeolgwa-reul yocheonghaneun yeonsan-imnida: toList(), toSet(), count(), first() / firstOrNull(), find(), fold(), sum() (yeoreo hyeongtae-ro), deungdeung. Terminal yeonsan-i silhaeng-eul sijakhabnida: element-deul-i pipeline-eul tonggwa-hagi sijakha여, gyeolgwa-ga eod-eojil ttae-kkaji jinhaengdoemnida.

Pyonhaeul wihae igeos-eul pyo-ro jeongrihaessseumnida. i pyo-ga “표준 라이브러리 jeonche-reul 완벽히 포괄”haneun geon 아니지만, 세상을 보는 올바른 그림-eul jwoipnida.

Yeonsan Bo-tong Sequenceeseo-neun… Mueos-eul banhwanhana? Gyesan-eul sijak-hana?
map { ... }
jung-gan
Sequence<R>
aniyo
filter { ... }
jung-gan
Sequence<T>
aniyo
take(n)
jung-gan
Sequence<T>
aniyo
toList()
terminal
List<T>
ne
count()
terminal
Int
ne
firstOrNull()
terminal
T?
ne
fold(initial) { ... }
terminal
R
ne

I pyo-man meori-eseo jabeugo isseumyeon, Sequence jubyun-ui daebubun-ui “sugang-ui misteori”ga sarajimnida.

4. wae “amugeotdo il-eo-na-ji anhass-eul-kka?”

Igeun jeongmal jeonhyeongjeog-in sanghwang-imnida: hakseong-i chein-eul sseugo, filter나 map an-eseo jigeum 당장 mueonga silhaengdoel geot-eul gidarida-ga, peurogeuraem-eul silhaenghamyeon… jeongjeok. Kotlin-i na-ui kodeu-reul 무시han geot gateun neukkim-i deul su itsseumnida. Kotlin-i manh-eun geot-eul hal su issjiman, a직 “telepathy”neun deureo-oji anhassseumnida: danji gyeolgwa-reul yocheonghaji anhass-eul ppun-imnida.

Ibeon-eneun filter와 map an-eseo myeongsi-jeog-euro chulryeok-eul haeseo “silhaeng”eul boneun 예제-reul bopsida.

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

    val seq = xs.asSequence()
        .filter { x ->
            println("filter: $x")
            x % 2 == 0
        }
        .map { x ->
            println("map: $x")
            x * 10
        }

    println("before toList")          // before toList
    val ys = seq.toList()
    println("after toList: $ys")      // after toList: [20, 40]
}

Yeogi-eseo-neun chulryeok sunseo-ga haengsim-imnida. meonjeo "before toList"ga boyigo, geu daeum-e ya "filter: ..."wa "map: ..."ga chulryeokdoemnida. I유는 toList() jeon-kkaji chein-i danji “seolmyeong”doeeosseul 뿐이gi ttaemun-imnida.

Ije—terminal yeonsan-i eomneun “munje-ui” 예제-reul bopsida:

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

    xs.asSequence()
        .filter { x ->
            println("check: $x")
            x > 1
        }

    println("done") // done
}

Chulryeok-eun "done"man naseumnida. "check: ..." neun jeonhyeo tteuji anhseumnida. i유는 Sequencereul mandeulgo, jung-gan dan-gye filterreul deohago, geu daeum… geu geos-eul jeonbu beorilyeosseugi ttaemun-imnida. Hyeongsikjeog-euro-neun pipeline-eul mandeulgo baro jib-e gago, g계-gi-reul kyeo-ji anh-eun geot-gwa gatseumnida.

5. i-reun terminal yeonsan-gwa materialization

I bu-bun-eseo-neun saeng-gak-eul jogeum se심하게 jeongnihaeya 합니다: terminal yeonsan-i silhaeng-eul sijakhajiman, hangsang jeonbureul kkeun-kkaji cheorihae-ya 하는 geon 아닙니다. Ye-reul deul-eo toList()neun jeongmal gyeolgwa element jeonbu-reul 모읍니다. Hajiman firstOrNull()은 cheoj-eum matneun element-eul chaj-eumyeon geu geot-eul eodneun sungan meomchul su itsseumnida.

Igeon “최적화를 위한 최적화”ga 아니라, yeonsan-ui uimi ttaemun-imnida: “cheoj-eum matneun geot”eul mul-eoss-eumyeon, gut-i geu daeum-kka-ji da dora-bol piryo-ga eopsseumnida.

Demonstration-eul bopsida:

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

    val firstBigEven = xs.asSequence()
        .filter { x ->
            println("filter: $x")
            x % 2 == 0
        }
        .map { x ->
            println("map: $x")
            x * 10
        }
        .firstOrNull { value ->
            println("firstOrNull predicate: $value")
            value >= 30
        }

    println("result: $firstBigEven") // result: 40
}

Juyeo bosaeyo: yeollyeol-eun 5 kkaji jeonbu cheorihaeya 할 의무ga eopsseumnida. firstOrNull { ... }ga man족haneun dap-eul chaj-eul ttae-kkaji-man banbokhamnida.

toList() neun materialization

Yeogi-eseo-neun toList()reul saram-ui mal-lo seolmyeonghae two면 joteumnida. toList()neun “jorihayeo jeopsi-e dama” button-gwa gatsseumnida. Sequence 안에서는 resep-gwa pipeline-i issseumnida. toList() ihu-eneun guchejeog-in Listga saenggimnida. Geu list-neun indekseu-ro ilgeul su 있고, chulryeokhal su 있고, ilbanjeog-in bangbeob-euro jeongryeolhal su 있고, Listreul gidae-haneun got-e jeondalhal su 있으며, han마디로 익숙한 seghye-ro dora올 수 있습니다.

“jeonhyeongjeog-in” 왕복 예제-reul bopsida:

fun main() {
    val raw = listOf("  food:120  ", " taxi:250", "food:80")

    val cleaned = raw.asSequence()
        .map { it.trim() }
        .filter { it.isNotEmpty() }
        .toList()

    println(cleaned) // [food:120, taxi:250, food:80]
}

toList() ihu-eneun da-si ilban list modeu-imnida. geurigo geugeun jeong상입니다: silje peurogeuraem-eseo Sequenceneun juro “naebu cheori modeu”ro sayongdoego, bak-euro-neun ilban keollekshyeon-eul dol려주거나, choejong sutja/munja열-eul dol려주는 gyeong-u-ga manseumnida.

6. BudgetBuddy aep-eul-eseo-ui Sequence

Ije uri-neun gyoyuk용 콘솔 aep-eul jogeum deo jinhanghaebogessseumnida (pyeon-ui-sang BudgetBuddyrago bureulg게요): i aep-eun jichul-eul bogwanhago, ripoteu-reul mandeul su itsseumnida. OO P eopsneun deiteo gujo aidea-reul dasi sanggi시키면, jichul-eun Triple(category, amount, note)cheoreom jeojanghal su itsseumnida. Igeon “wanbyeok”hajin 않지만, hyeonjae kursu dan-gye-eseoneun chungbun합니다.

Jageun deiteo seuteob-euro sijakhaebopsida:

typealias Expense = Triple<String, Int, String>

fun main() {
    val expenses = listOf(
        Expense("food", 120, "lunch"),
        Expense("taxi", 250, "airport"),
        Expense("food", 80, "coffee"),
        Expense("books", 500, "kotlin"),
    )

    println(expenses.size) // 4
}

Kategoria "food" byeol ripoteu 예제

Daeum chein-eul mandeul-eobopsida:

cheoeum-eun "food"man namgigo, geu daeum jichul-eul ripoteu munjang-euro 바꾸고, kkeun-eseo munjang list-reul 모읍니다.

typealias Expense = Triple<String, Int, String>

fun main() {
    val expenses = listOf(
        Expense("food", 120, "lunch"),
        Expense("taxi", 250, "airport"),
        Expense("food", 80, "coffee"),
    )

    val lines = expenses.asSequence()
        .filter { (cat, _, _) -> cat == "food" }
        .map { (cat, amount, note) -> "$cat: $amount ($note)" }
        .toList()

    println(lines) // [food: 120 (lunch), food: 80 (coffee)]
}

Yeogi-eseo deiteo-ga jageun-de, wae Sequencega uimi가 있을까요? 솔직한 답: i jeongdo 크기에서는 keu-ge jungyohaji 않습니다. Hajiman “jung-gan dan-gye-neun terminal-i eop으면 silhaengdoeji 않는다”neun model-eul sumseup-hagi-e jeong말 좋은 yeonseup-imnida.

“filterreul deohassneunde, amugeotdo 바뀌지 않아요”

BudgetBuddy ripoteu-reul mandeul ttae jaju 나오는 실수-ga itsseumnida: hakseong-i Sequencereul gusung하고, geuge “automatically list-reul update”hal geot-eul gidarijiman, chein-eul eodideuro 저장하지도, materialize 하지도 않습니다.

Daeum-eun jal못된 접근 예입니다 (compile-doego, amugeotdo an 합니다—월요일 아침의 eotteon hakseongdeulcheoreom):

typealias Expense = Triple<String, Int, String>

fun main() {
    val expenses = mutableListOf(
        Expense("food", 120, "lunch"),
        Expense("taxi", 250, "airport"),
    )

    expenses.asSequence()
        .filter { (cat, _, _) -> cat == "food" }

    println(expenses.size) // 2
}

Wae 2iji, 1i anil까요? I유는 Sequenceeseo-ui filterga “list-eseo sakje”haneun geos-i 아니라, saeroun sequence (seontaek resep)reul mandeuneun geos-i기 ttaemun-imnida. Geu gyeolgwa-reul sayonghaji도 않았고, terminal-ro “gyeolgwa jwo”라고 yocheong하지도 않았습니다.

Ol바른 bangbeob-eun gyeolgwa-reul eodgo, geugeol myeongsi-jeog-euro sayonghaneun geosimnida:

typealias Expense = Triple<String, Int, String>

fun main() {
    val expenses = listOf(
        Expense("food", 120, "lunch"),
        Expense("taxi", 250, "airport"),
    )

    val foods = expenses.asSequence()
        .filter { (cat, _, _) -> cat == "food" }
        .toList()

    println(foods.size) // 1
}

7. Sequence wa side effect

Lazyseong-eul boneun sun-gan, map/filter 안에서 printlneul sseugo sip-eojimnida. Gyoyuk용으론 mut-jarang-haejiman, “silje yongdo”ro도—log 남기기, 바깥 변수에 카운트 누적하기, 상태 update—를 하고 싶어질 수 있습니다. Ganeunghajiman, geugeun geumbang 함정-euro byeonhamnida.

Munje-neun, lazy model-eseoneun na-ui kodeuga eonje jeongmal silhaengdoelji “jikgwanjeok”euro 말하기가 eoryeowojineun 데 있습니다. Kodeu-neun nuguga gyeolgwa-reul yocheong할 때 silhaengdoego, jeongmal piryo한 횟수만큼만 silhaengdoemnida. Maneil terminal yeonsan-eul uidochi anhge du beon bulleobeorimyeon (ye: gat-eun yeollyeol-e daehae chein-eul dasi gusunghayeo du beon toList()), side effect-do du beon il-eonam니다. Geureomyeon “Kotlin-i element-reul bokjehae”라고 saeng-gakhagi 쉽지만, silje-ro bokjedoeneun geon na-ui 로직입니다.

Ttareoseo joteun 습관은 이겁니다: map/filterneun pure하게 (side effect 없이) 유지하고, “mueos-i il-eonaneunji bogo sipda”myeon, jamkkan printlneul sseoseo 확인하거나, 프로그램 의미에 영향을 주지 않는 별도 dan-gye-ro 분리해서 확인하세요.

8. Sequence sayong si jaju 하는 실수

Sil-su No.1: terminal yeonsan-i eopseum — “amugeotdo il-eona-ji 않음”.
Gajang in-gihaneun 함정입니다. asSequence().filter { ... }.map { ... }cheoreom chein-eul mandeulgo, list-ga imi “dareun list”ga doeeoss-eul geot이라 기대합니다. Hajiman Sequenceneun lazy resep이지, wansungdoen gyeolgwa-ga 아닙니다. Terminal dan-gye-ga piryo합니다: toList(), count(), firstOrNull(), fold() deung.

Sil-su No.2: Sequencega “wonbon keollekshyeon-eul 바꾼다”고 기대함.
filterwa mapeun MutableListeseo element-reul jiuji도 않고, geu list-reul deopeo-sseuji도 않습니다. Geudeul-eun saeroun gyeolgwa (ttoneun saeroun “pipeline”)reul mandeul 뿐입니다. Jeongmal로 sakjehaeya 한다면, geugeun dareun munje이고 dareun kodeu가 piryo하며, Sequencega manna-neun “magic broom”i 아닙니다.

Sil-su No.3: map/filter 안의 side effect로 인해 hon란이 saenggim.
map 안에서 chulryeok을 하거나, 카운터를 올리거나, file-e sse거나, 바깥 변수를 바꾸면, 프로그램 의미가 “gyeosan si점”에 묶여 버립니다. Lazy model-eseo gyeosan 시점은 terminal yeonsan에 달려 있어서, 코드가 예측하기 더 어렵고 디버깅도 힘들어집니다.

Sil-su No.4: Sequencereul “jong-gyo”cheoreom da루기.
Gakkeum hakseong-i “jeonmun-ga-cheoreom” boyeogo 싶어서 모든 chein-e asSequence()reul kkeuneo넣기 시작합니다. Jageun deiteo-eseo-neun i익이 거의 없고, gakkeum-eun 가독성을 떨어뜨리기도 합니다: eonje gyeolgwa-reul eodneunji 파악하기가 더 어려워지기 때문입니다. Dae신 ireohge dan순한 gyuchik-eul gajigo isseuseyo: Sequenceneun chein-ui lazy silhaeng-i jungyohan gyeong-u-e yuyong하며, geu bak-eseoneun Liste dae-han ilban yeonsan-eul sayongha도 achuie joteun, ilgih swiun 도구입니다.

Sil-su No.5: gyeolgwa-ga keollekshyeon-euro piryo한데 materialization-eul 하지 않음.
Ripoteu-eseo ajeong말 jaju na오는 케이스입니다: Sequence<String>reul mandeulgo, geu daeum-e geugeol List<String>인 것처럼 chulryeok하려고 하거나, list-reul gidae-haneun got-e jeondal하려고 합니다. Haegyeol-eun dan순합니다: kkeun-e toList() (ttoneun dareun terminal dan-gye)reul butyeo, gyeolgwa-ro bu터 jak업하세요.

1
과제
Kotlin SELF, 레벨 25, 레슨 2
잠금
보너스 필터
보너스 필터
1
과제
Kotlin SELF, 레벨 25, 레슨 2
잠금
지연 파이프라인
지연 파이프라인
1
과제
Kotlin SELF, 레벨 25, 레슨 2
잠금
빠른 검색
빠른 검색
1
과제
Kotlin SELF, 레벨 25, 레슨 2
잠금
지출 정리
지출 정리
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION