Scala 中 foldLeft 和 reduceLeft 的区别 [英] difference between foldLeft and reduceLeft in Scala

查看:22
本文介绍了Scala 中 foldLeft 和 reduceLeft 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经了解了 foldLeftreduceLeft

左折叠:

  • 必须传递初始值

reduceLeft:

  • 将集合的第一个元素作为初始值
  • 如果集合为空则抛出异常

还有其他区别吗?

有两种功能相似的方法有什么具体原因吗?

Any specific reason to have two methods with similar functionality?

推荐答案

在给出实际答案之前,这里有几点需要提及:

Few things to mention here, before giving the actual answer:

  • 你的问题与left没有任何关系,而是关于reduce和folding的区别
  • 区别根本不在于实现,只需查看签名即可.
  • 这个问题与 Scala 没有任何关系,而是关于函数式编程的两个概念.
  • Your question doesn't have anything to do with left, it's rather about the difference between reducing and folding
  • The difference is not the implementation at all, just look at the signatures.
  • The question doesn't have anything to do with Scala in particular, it's rather about the two concepts of functional programming.

回到你的问题:

这是 foldLeft 的签名(也可以是 foldRight 对于我要提出的观点):

Here is the signature of foldLeft (could also have been foldRight for the point I'm going to make):

def foldLeft [B] (z: B)(f: (B, A) => B): B

这里是 reduceLeft 的签名(同样方向在这里无关紧要)

And here is the signature of reduceLeft (again the direction doesn't matter here)

def reduceLeft [B >: A] (f: (B, A) => B): B

这两个看起来非常相似,因此引起了混淆.reduceLeftfoldLeft 的特例(顺便说一下,这意味着您有时可以通过使用它们中的任何一个来表达相同的东西).

These two look very similar and thus caused the confusion. reduceLeft is a special case of foldLeft (which by the way means that you sometimes can express the same thing by using either of them).

当你在 List[Int] 上调用 reduceLeft 时,它实际上会将整个整数列表缩减为一个单一的值,它的类型是 Int(或 Int 的超类型,因此 [B >: A]).

When you call reduceLeft say on a List[Int] it will literally reduce the whole list of integers into a single value, which is going to be of type Int (or a supertype of Int, hence [B >: A]).

当你在 List[Int] 上调用 foldLeft 时,它会将整个列表(想象一下滚动一张纸)折叠成一个值,但是这个值甚至不必与 Int 相关(因此是 [B]).

When you call foldLeft say on a List[Int] it will fold the whole list (imagine rolling a piece of paper) into a single value, but this value doesn't have to be even related to Int (hence [B]).

这是一个例子:

def listWithSum(numbers: List[Int]) = numbers.foldLeft((List.empty[Int], 0)) {
   (resultingTuple, currentInteger) =>
      (currentInteger :: resultingTuple._1, currentInteger + resultingTuple._2)
}

该方法接受一个 List[Int] 并返回一个 Tuple2[List[Int], Int](List[Int], Int).它计算总和并返回一个包含整数列表的元组,它是总和.顺便说一下,列表是向后返回的,因为我们使用了 foldLeft 而不是 foldRight.

This method takes a List[Int] and returns a Tuple2[List[Int], Int] or (List[Int], Int). It calculates the sum and returns a tuple with a list of integers and it's sum. By the way the list is returned backwards, because we used foldLeft instead of foldRight.

观看One Fold 来统治它们以获得更深入的解释.

Watch One Fold to rule them all for a more in depth explanation.

这篇关于Scala 中 foldLeft 和 reduceLeft 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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