foldRight

fold 의 반대 오른쪽 -> 왼쪽

public inline fun <T,R> List<T>.foldRight(initial: R,
opertion: (T, acc: R) -> R): R {
    var accumulator = initial
    if (!isEmpty()) {
        val iterator = listIterator(size)
        while (iterator.hasPrevious()) {
            accumulator = operation(iterator.previous(), accumulator)
        }
    }    
    return accumulator
}

val list = listOf(1, 2, 3, 4, 5)

pritln(list.foldRight(0, { pre, acc -> pre + acc }))  // 15

Last updated