Kotlin中折叠和缩小之间的基本区别是什么?什么时候使用? [英] What is basic difference between fold and reduce in Kotlin? When to use which?

查看:89
本文介绍了Kotlin中折叠和缩小之间的基本区别是什么?什么时候使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Kotlin的基础知识,我对Kotlin中的这两个函数fold()和reduce()感到很困惑,谁能给我一个具体的例子来区分它们吗?

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

推荐答案

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).


reduce doesn't take an initial value, but instead starts with the first element of the collection as the accumulator (called sum in the following example).

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

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中折叠和缩小之间的基本区别是什么?什么时候使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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