在scala澄清中折叠

时间:2016-05-24 13:15:54

标签: scala functional-programming fold

想通过折叠操作来改进代码片段

此代码有效

var r = 0
arr.foreach { s =>
  val count = arr.count(_ == s)
  if (count > r) r = count
}

但是如果有折叠。我的类型有错误。

Error:(44, 49) type mismatch;
 found   : (Int, String) => Any
 required: (Any, Any) => Any
      arr.fold(0: Int)((result: Int, s: String) => {
                                                ^

  arr.fold(0: Int)((result: Int, s: String) => {
    val count = arr.count(_ == s)
    if (count > result) count
  })

有什么问题?

1 个答案:

答案 0 :(得分:2)

如果您要查找数组中出现次数最多的字符串,可以使用groupBy

val arr = Array("yuval", "yuval", "david")
arr.groupBy(identity).mapValues(_.length).max._2

arr: Array[String] = Array(yuval, yuval, david)
res1: Int = 2

如果你真的想跳到使用折叠的圈子,你需要foldLeftfoldRight,它们会为序列中的每个值传递累加器:

val arr = Array("yuval", "yuval", "david")
val aggregatedMap = arr.foldLeft(Map.empty[String, Int].withDefaultValue(0)) {
  case (map, value) => map.updated(value, map(value) + 1)
}

println(aggregatedMap.max._2)