Kotlin Fold Reduce


Kotlin Reduce

剛開始寫 Kotlin 的時候

Array, ArrayList, List, MutableList

就被這四個搞死了,因為 Swift 只有一種叫做 Array

高階函數

swift -> map, filter, reduce

kotlin -> map, filter, reduce, fold


Kotlin 的 reduce 不等於 Swift 的 reduce

inline fun <S, T : S> Array<out T>.reduce(
    operation: (acc: S, T) -> S
): S


Kotlin Fold

Kotlin 的 fold 等於 Swift 的 reduce

inline fun <T, R> Array<out T>.fold(
    initial: R, 
    operation: (acc: R, T) -> R
): R


莫名其妙就跳坑了 囧


需要注意的是 Reduce will throw error in empty collection

public inline fun <S, T : S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S {
    val iterator = this.iterator()
    if (!iterator.hasNext()) 
        throw UnsupportedOperationException("Empty collection can't be reduced.")
    var accumulator: S = iterator.next()
    while (iterator.hasNext()) {
        accumulator = operation(accumulator, iterator.next())
    }
    return accumulator
}