简体   繁体   English

Scala:关于“ foldLeft”的奇怪行为

[英]Scala: On strange behavior of `foldLeft`

Define: 限定:

val a = List(1, 2, 3, 4, 5, 6, 7)

Consider the following line with foldLeft : 考虑以下带有foldLeft行:

a.foldLeft(""){case (num, sum) => sum + (num.toString + "-")}

My expectation was that the program is going to do: 我的期望是该程序将要执行的操作:

((((( "7-" + "6-" ) + "5-" ) + "4-" ) + "3-" ) + "2-" ) + "1-" (((((((“ 7-” +“ 6-”)+“ 5-”)+“ 4-”)+“ 3-”)+“ 2-”)+“ 1-”

which is 7-6-5-4-3-2-1- 这是7-6-5-4-3-2-1-

But what I get is: 7654321------- . 但是我得到的是: 7654321------- Why is this the case? 为什么会这样呢?

You mixed up the parameters to foldLeft . 您将参数混合到foldLeft Check the documentation for List.foldLeft . 检查文档List.foldLeft Note that the z "zero" value has the same type as the second parameter in the function argument, not the first. 请注意, z “零”值具有与函数参数中第二个参数(而不是第一个参数)相同的类型。

This should work closer to expected: 这应该更接近预期:

a.foldLeft(""){case (sum, num) => sum + (num.toString + "-")}
// res0: String = 1-2-3-4-5-6-7-

However, if you want the numbers in reverse-order, then you might want to use foldRight . 但是,如果您希望数字按相反顺序排列,则可能需要使用foldRight Maybe this is actually what you were going for in the first place (notice that the arguments num and sum are in the same order you gave): 也许这实际上是您首先要使用的(请注意,参数numsum的顺序与您给定的顺序相同):

a.foldRight(""){case (num, sum) => sum + (num.toString + "-")}
// res1: String = 7-6-5-4-3-2-1-

From your expectation, I expect you expected foldRight behavior: 从您的期望,我期望您期望foldRight行为:

scala> val a = List(1, 2, 3, 4, 5, 6, 7)
a: List[Int] = List(1, 2, 3, 4, 5, 6, 7)

scala> a.foldRight(""){case (num, sum) => sum + (num.toString + "-")}
res0: String = 7-6-5-4-3-2-1-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM