Kotlin 中 fold 和 reduce 的区别,何时使用哪个? [英] Difference between fold and reduce in Kotlin, When to use which?

查看:30
本文介绍了Kotlin 中 fold 和 reduce 的区别,何时使用哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Kotlin 中的 fold()reduce() 两个函数很困惑,谁能给我一个具体的例子来区分它们?

I am pretty confused with both functions fold() and reduce() in Kotlin, can anyone give me a concrete example that distinguishes both of them?

推荐答案

fold 接受一个初始值,您传递给它的 lambda 的第一次调用将接收该初始值和集合的第一个元素作为参数.

fold takes an initial value, and the first invocation of the lambda you pass to it will receive that initial value and the first element of the collection as parameters.

以下面的代码为例,计算一个整数列表的总和:

For example, take the following code that calculates the sum of a list of integers:

listOf(1, 2, 3).fold(0) { sum, element -> sum + element }

对 lambda 的第一次调用将使用参数 01.

The first call to the lambda will be with parameters 0 and 1.

如果您必须为操作提供某种默认值或参数,则具有传入初始值的能力非常有用.例如,如果您正在寻找列表中的最大值,但由于某种原因想要返回至少 10,您可以执行以下操作:

Having the ability to pass in an initial value is useful if you have to provide some sort of default value or parameter for your operation. For example, if you were looking for the maximum value inside a list, but for some reason want to return at least 10, you could do the following:

listOf(1, 6, 4).fold(10) { max, element ->
    if (element > max) element else max
}

<小时>

reduce不接受初始值,而是从集合的第一个元素作为累加器开始(在以下示例中称为 sum).

例如,让我们再次对整数求和:

For example, let's do a sum of integers again:

listOf(1, 2, 3).reduce { sum, element -> sum + element }

这里对 lambda 的第一次调用将使用参数 12.

The first call to the lambda here will be with parameters 1 and 2.

当您的操作不依赖于您应用它的集合中的值以外的任何值时,您可以使用 reduce.

You can use reduce when your operation does not depend on any values other than those in the collection you're applying it to.

这篇关于Kotlin 中 fold 和 reduce 的区别,何时使用哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆