【发布时间】:2014-08-04 16:07:31
【问题描述】:
如何在 Scala 中使用 reduce 函数?有这样的内置功能吗? 我已经实现了一个程序来查找 scala 中的字数。
object count {
def main(args: Array[String]) {
val fruits = List("apple", "apple", "orange", "apple", "mango", "orange")
val word = fruits.flatMap(_.split("\n"))
val Map = word.map(word => (word,1)).groupBy(_._1)
val reduce = Map.map(word => (word._1,word._2.foldLeft(0)((sum,c) => sum+ c._2)))
println(reduce) }}
如何用reduce函数替换foldleft?
【问题讨论】:
-
有一个
reduce,但foldLeft在这种情况下更合适,因为reduce不接受默认值,所以它会在空列表上失败。 -
如果我们改用reduce,函数会是什么样子?
-
我刚刚对此表示赞同。然而,在当前状态下,它的措辞方式需要改进......但我仍然认为这个问题具有一定的教学价值,并且对中级/初学者 scala 用户很有用
标签: scala mapreduce word-count