在Fold方法中键入mismatch scala

时间:2015-10-29 10:32:39

标签: scala generics types scala-collections

我正在学习Scala,我在编写简单的reducer函数时遇到了一些麻烦。我想计算一个值出现在列表中的次数。因此,我编写了一个reducer / folding函数,它将一个不可变映射作为初始值,然后迭代列表"更新"地图,其中包含值在列表中显示的次数。非常简单的东西,但我遇到了类型系统的问题(啊......在JavaScript和Python上花了太多时间)

这是功能:

    lapply(1 : 100, function (i) { HoltWinters(mydata[, group == i], 
beta = FALSE, gamma = FALSE) } )

我无法理解为什么会出现以下类型错误:

def times(chars: List[Char]): List[(Char, Int)] = {

  val acc:Map[Char, Int] = Map()

  def count(acc:Map[Char, Int], c:Char) = {
    if (acc contains c) acc + (c -> (acc(c) + 1))
    else acc + (c -> 1)
  }

  chars.fold(acc)(count).toList
}

[error] /Users/giuseppe/courses/scala_functional_programing/lessons/week_4/assignment/src/main/scala/patmat/Huffman.scala:85: type mismatch; [error] found : (Map[Char,Int], Char) => scala.collection.immutable.Map[Char,Int] [error] required: (Any, Any) => Any [error] chars.fold(acc)(count) [error] ^ [error] /Users/giuseppe/courses/scala_functional_programing/lessons/week_4/assignment/src/main/scala/patmat/Huffman.scala:85: type mismatch; [error] found : Any [error] required: List[(Char, Int)] [error] chars.fold(acc)(count) [error] ^ [error] two errors found 的子类型是Map[Char, Int]吗?

*编辑*

更有趣的是,我刚刚发现,如果我使用Any,它就能正常运行。 :confused:为什么??

任何帮助都会非常感激。谢谢

1 个答案:

答案 0 :(得分:2)

看起来你需要foldLeft功能而不是折叠。 它有适当的签名。

def foldLeft[B](z: B)(f: (B, A) => B): B = { // in your case B is Map and A is Char
def fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1 = foldLeft(z)(op) // in your case arguments of count functions should be same