Kotlin 中,reduce()fold()函数式编程中常用的高阶函数。它们都是对调集中的元素进行聚合操作的函数,将一个调集中的元素缩减成一个单独的值。它们的运用方式非常相似,但是回来值略有不同。下面是它们的区别:

  • reduce() 函数是对调集中的一切元素进行聚合处理,并回来最终一个兼并处理值。
  • fold() 函数除了兼并一切元素之外,还能够接受一个初始值,并将其与聚合成果一同回来。注:假如调集为空的话,只会回来初始值。

reduce示例

1、运用 reduce() 函数核算列表中一切数字的总和:

fun reduceAdd() {
        val list = listOf(1, 2, 3, 4, 5)
        val sum = list.reduce { acc, i ->
            println("acc:$acc, i:$i")
            acc + i
        }
        println("sum is $sum")  // 15
    }

履行成果:

acc:1, i:2
acc:3, i:3
acc:6, i:4
acc:10, i:5
sum is 15

2、运用 reduce() 函数核算字符串列表中一切字符串的拼接成果:

val strings = listOf("apple", "banana", "orange", "pear")
val result = strings.reduce { acc, s -> "$acc, $s" }
println(result) // apple, banana, orange, pear

履行成果:

apple, banana, orange, pear

fold示例

1、运用 fold() 函数核算列表中一切数字的总和,并在其基础上加上一个初始值:

val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.fold(10) { acc, i -> acc + i }
println(sum) // 25

履行成果为:

acc:10, i:1
acc:11, i:2
acc:13, i:3
acc:16, i:4
acc:20, i:5
sum is 25

2、运用 fold() 函数将列表中的一切字符串连接起来,并在其基础上加上一个初始值:

val strings = listOf("apple", "banana", "orange", "pear")
val result = strings.fold("Fruits:") { acc, s -> "$acc $s" }
println(result) // Fruits: apple banana orange pear

履行成果:

Fruits: apple banana orange pear

源码解析

  • reduce()Kotlin规范库的完成如下:
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
}

从代码中能够看出,reduce函数接纳一个operation参数,它是一个lambda表达式,用于聚合核算。reduce函数首先获取调集的迭代器,并判别调集是否为空,若为空则抛出反常。然后经过迭代器对调集中的每个元素进行遍历操作,对元素进行聚合核算,将核算成果作为累加器,传递给下一个元素,直至聚合一切元素。最终回来聚合核算的成果。

  • fold()Kotlin规范库的完成如下:
public inline fun <T, R> Iterable<T>.fold(
    initial: R,
    operation: (acc: R, T) -> R
): R {
    var accumulator: R = initial
    for (element in this) {
        accumulator = operation(accumulator, element)
    }
    return accumulator
}

从代码中能够看出,fold函数接纳两个参数,initial参数是累加器的初始值,operation参数是一个lambda表达式,用于聚合核算。

fold函数首先将初始值赋值给累加器,然后对调集中的每个元素进行遍历操作,对元素进行聚合核算,将核算成果作为累加器,传递给下一个元素,直至聚合一切元素。最终回来聚合核算的成果。

总结

  • reduce()适用于不需求初始值的聚合操作,fold()适用于需求初始值的聚合操作。
  • reduce()操作能够直接回来聚合后的成果,而fold()操作需求经过lambda表达式的回来值来更新累加器的值。

在运用时,需求根据详细场景来挑选运用哪个函数。