
82
|
第
4
章
而元素是 Int 值。
像示例中这样使用 fold 会比典型的求和操作强大得多。
参阅
阶乘问题也会在 4.3 节中讨论。使用 reduce 而不是 fold 在 4.2 节中介绍。
4.2
使用
reduce
函数进行归约
问题
如何在不为累加器设置初始值的情况下对非空集合进行归约。
解决方案
使用 reduce 操作代替 fold。
讨论
reduce 函数与 4.1 节中讨论过的 fold 函数类似。但它不需要给累加器设置初始值。
Iterable 上的 reduce 函数签名如下:
inline fun <S, T : S> Iterable<T>.reduce(
operation: (acc: S, T) -> S
): S
reduce 函数与 fold 函数几乎完全相同,并且其用途也相同。它们的最大区别是
reduce 函数没有为累加器提供初始值的参数。因此,累加器将使用集合中的第一个值
进行初始化。
示例 4-6 展示了标准库中 reduce 的实现
示例 4-6:reduce 函数的实现
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 ...