Scala - foldLeft类型推断失败

non*_*com 3 types scala fold

在我的代码中,我有以下内容:

  type Occurrences = List[(Char, Int)]

  def subtract(x: Occurrences, y: Occurrences): Occurrences = {
    val yMap = y.toMap
    x foldLeft (List[(Char, Int)]()) {  // ERROR
        case (a: List[(Char, Int)], xe: (Char, Int)) =>
        if(yMap.contains(xe._1)) (xe._1 -> (xe._2 - yMap(xe._1))) :: a
        else a
    }
  }
Run Code Online (Sandbox Code Playgroud)

它在编译时失败,就{在代码中的错误标记之前.错误消息如下:

扩展函数缺少参数类型必须完全知道匿名函数的参数类型.(SLS 8.5)预期类型为:Int

1)怎么会这样?据我所知,这里没有错误解释类型信息的余地,我在互联网上发现了很多这样的例子.我该如何解决这个问题?

2)为什么它认为预期的类型Int毕竟是?

kir*_*uku 8

发生错误的原因是您编写的xs foldLeft (init) (f)而不是(xs foldLeft init)(f)xs.foldLeft(init)(f).

前者不起作用,因为Scalas运算符符号规则只允许在表单中发生调用时留下点和圆括号obj method param,foldLeft因为它有两个参数列表.