Scala - foldLeft 类型推断失败

标签 scala types 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
    }
  }

它在编译时失败,在代码中错误标记之前的 { 处。错误信息如下:

missing parameter type for expanded function The argument types of an anonymous function must be fully known. (SLS 8.5) Expected type was: Int

1) 怎么可能?据我所知,这里没有对类型信息进行误解的余地,我在互联网上找到了很多这样的例子。我该如何解决?

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

最佳答案

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

前者不起作用,因为 Scalas 运算符符号规则只允许在 obj 方法参数 形式中发生调用时留下点和括号,而 foldLeft< 则不是这种情况 因为它有两个参数列表。

关于Scala - foldLeft 类型推断失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13108527/

相关文章:

functional-programming - (方案)检查项目列表是否都满足逻辑关系

bash - 从脚本执行 SBT 命令

scala - 让 Intellij 自动格式化代码并将类型添加到变量/返回/参数

scala - Spark : Custom key compare method for reduceByKey

scala - 连接许多列的更好方法?

c# - 为什么 C#.net 中的表达式主体不能使用 int、double 或 bool 类型的属性?

没有重复定义的 C++ 模板匹配类型

go - 从 slice 中移除接口(interface)项

haskell - 在左侧折叠中构建列表的最有效方法?

scala - 在 Scala 中使用 FoldRight 的 FoldLeft