地图上的 Scala foldLeft

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4178706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:33:41  来源:igfitidea点击:

Scala foldLeft on Maps

scalascala-2.8scala-collections

提问by Pengin

How do you use Map.foldLeft? According to the docsit looks like

你如何使用 Map.foldLeft?根据文档,它看起来像

foldLeft [B] (z: B)(op: (B, (A, B)) ? B) : B

But I'm having difficulty:

但我有困难:

Map("first"->1,"second"->2).foldLeft(0)((a,(k,v)) => a+v )

error: not a legal formal parameter

Map("first"->1,"second"->2).foldLeft(0)((a,(k,v)) => a+v )

错误:不是合法的形式参数

The error points to the open bracket in front of k.

错误指向k前面的开括号。

回答by Debilski

If you want to use the (a, (k, v))syntax, you need to advise the compiler to use pattern matching.

如果要使用(a, (k, v))语法,则需要建议编译器使用模式匹配。

Map("first"->1, "second"->2).foldLeft(0){ case (a, (k, v)) => a+v }

Note that a casestatement requires curly braces.

请注意,case语句需要花括号。

回答by Thomas Jung

I think, you can't do the pattern match on tuples as you expect:

我认为,您不能像预期的那样对元组进行模式匹配:

Map("first"->1,"second"->2).foldLeft(0)((a, t) => a + t._2)

Actually, using values and sum is simpler.

实际上,使用 values 和 sum 更简单。

Map("first"->1,"second"->2).values.sum

回答by Theo

The trick is to use a partial function as the code block, in other words you add a casestatement that matches on the arguments:

诀窍是使用部分函数作为代码块,换句话说,您添加一个case与参数匹配的语句:

Map("first" -> 1, "second" -> 2).foldLeft(0) { case (a, (k, v)) => a + v }

回答by oxbow_lakes

This is not really an answer to your question but I found it useful when starting out with folds, so I'll say it anyway! Note that the /:method "alias" for foldLeftcan be clearer for two reasons:

这不是你问题的真正答案,但我发现它在开始折叠时很有用,所以我还是要说!请注意,由于两个原因,/:方法“别名”foldLeft可能更清晰:

xs.foldLeft(y) { (yy, x) => /* ... */ }

(y /: xs) { (yy, x) => /* ... */ }

Note that in the second line:

请注意,在第二行中:

  • it's more clear that the value yis being folded intothe collection xs
  • you can easily remember the ordering of the Tuple2argument is the same as the ordering of the method "call"
  • 更清楚的是,价值y正在被折叠到收藏中xs
  • 您可以轻松记住Tuple2参数的顺序与方法“调用”的顺序相同