포스트

Kotlin - .partition(), .reduce(), .fold()

컬렉션(List, Iterable) 확장 함수

.partition()

하나의 리스트를 조건을 만족하는 요소와 만족하지 않는 요소로 나누어 두 리스트로 분리하는 함수.
반환 자료형이 Pair() 이다.

1
2
3
4
5
6
7
8
9
10
11
12
public inline fun IntArray.partition(predicate: (Int) -> Boolean): Pair<List<Int>, List<Int>> {  
    val first = ArrayList<Int>()  
    val second = ArrayList<Int>()  
    for (element in this) {  
        if (predicate(element)) {  
            first.add(element)  
        } else {  
            second.add(element)  
        }  
    }  
    return Pair(first, second)  
}

사용 예시

1
2
3
4
5
6
7
fun main() {  
    val nums = intArrayOf(1,2,3,4,5,6,7,8,9)  
    val (odd, even) = nums.partition { it % 2 == 1 }  
  
    println("odd: $odd")  
    println("even: $even")  
}
  • odd: [1, 3, 5, 7, 9]
    even: [2, 4, 6, 8]


.reduce()

첫 번째 요소를 초기 값으로 사용하여 컬렉션의 요소들을 누적 연산하고, 그 결과를 반환하는 함수.

1
2
3
4
5
6
7
8
9
public inline fun IntArray.reduce(operation: (acc: Int, Int) -> Int): Int {  
    if (isEmpty())  
        throw UnsupportedOperationException("Empty array can't be reduced.")  
    var accumulator = this[0]  
    for (index in 1..lastIndex) {  
        accumulator = operation(accumulator, this[index])  
    }  
    return accumulator  
}

사용 예시

1
2
3
4
5
6
  fun main() {  
    val nums = intArrayOf(1,2,3,4,5,6,7,8,9)  
  
    println("최대값 구하기: ${nums.reduce { acc, i -> max(acc, i) }}")  
    println("요소들의 곱 구하기: ${nums.reduce { acc, i -> acc * i }}")
}
  • 최대값 구하기: 9
    요소들의 곱 구하기: 362880


.fold()

초기 값을 직접 지정해서 컬렉션의 요소들을 누적 연산하고, 그 결과를 반환하는 함수.

1
2
3
4
5
public inline fun <R> IntArray.fold(initial: R, operation: (acc: R, Int) -> R): R {  
    var accumulator = initial  
    for (element in this) accumulator = operation(accumulator, element)  
    return accumulator  
}

reduce() 와의 차이점:

  1. reduce()는 첫번째 요소를 초기값으로 사용하기 때문에 초기값을 정할 수 없으며,
    빈 컬렉션에선 사용할 수 없다.
  2. fold()는 반환 타입을 자유롭게 변경할 수 있다.

사용 예시

1
2
3
4
5
6
7
fun main() {  
    val nums = intArrayOf(101,2,33,4,5,6,77,8,9)  
      
    println("최대값 구하기1: ${nums.fold(100) { acc, i -> max(acc, i) }}")  
    println("최대값 구하기2: ${nums.fold(200) { acc, i -> max(acc, i) }}")  
    println("숫자 이어붙이기: ${nums.fold("") { acc, i -> acc + i }}")
}
  • 최대값 구하기1: 101
    최대값 구하기2: 200
    숫자 이어붙이기: 1012334567789
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.