본문 바로가기
코틀린/[Aggregation] 집계 작업

[Kotlin][Collection] fold / foldIndexed

by jinwo_o 2024. 8. 8.

초기값부터 시작하여 현재 누산기 값과 각 요소에 왼쪽에서 오른쪽으로 연산을 적용하여 값을 누적합니다.

배열이 비어 있으면 지정된 초기 값을 반환합니다.

public inline fun <T, R> Iterable<T>.fold(initial: R, operation: (acc: R, T) -> R): R {
    var accumulator = initial
    for (element in this) accumulator = operation(accumulator, element)
    return accumulator
}


val strings = listOf("b", "c", "d")
println(strings.fold("a") { acc, string -> acc + string }) // abcd

 

초기 값부터 시작하여 왼쪽에서 오른쪽으로 현재 누산기 값과 원본 컬렉션의 인덱스가 있는 각 요소에 연산을 적용하여 값을 누적합니다. 컬렉션이 비어 있으면 지정된 초기 값을 반환합니다.

public inline fun <T, R> Iterable<T>.foldIndexed(initial: R, operation: (index: Int, acc: R, T) -> R): R {
    var index = 0
    var accumulator = initial
    for (element in this) accumulator = operation(checkIndexOverflow(index++), accumulator, element)
    return accumulator
}


val strings = listOf("b", "c", "d")
println(strings.foldIndexed("a") { index, acc, string -> acc + string + index }) // ab0c1d2

 

fold - Kotlin Programming Language

 

kotlinlang.org

 

foldIndexed - Kotlin Programming Language

 

kotlinlang.org