缺少参数类型

Ele*_*fee 4 types scala

我在Scala中重写了一系列Haskell函数,并遇到了一个我似乎无法解释的编译错误

错误如下:

missing parameter type
    def group[A](xs: List[A]): List[List[A]] = groupBy((a, b) => a == b, xs)
                                                        ^
missing parameter type
    def group[A](xs: List[A]): List[List[A]] = groupBy((a, b) => a == b, xs)
                                                           ^
Run Code Online (Sandbox Code Playgroud)

代码如下:

object Stuff {
  def main(args: Array[String]): Unit = {
    val lst = List(1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 5, 6, 7)
    println(group(lst))
  }

  def group[A](xs: List[A]): List[List[A]] = groupBy((a, b) => a == b, xs)
  def groupBy[A](fun: (A, A) => Boolean, input: List[A]): List[List[A]] = // stuff
}
Run Code Online (Sandbox Code Playgroud)

我不确定这里发生了什么,为什么它抱怨缺少参数类型.据我所知,一切都已定义

Mik*_*ame 6

如果在groupBy调用站点提供显式泛型类型参数,它将编译:

def group[A](xs: List[A]): List[List[A]] = groupBy[A]((a, b) => a == b, xs)
Run Code Online (Sandbox Code Playgroud)

请参阅此文章,了解为什么Scala的类型推断在这种情况下失败.

如果groupBy使用curried参数列表编写,则应正确推断类型信息:

def group[A](xs: List[A]): List[List[A]] = groupBy(xs)((a, b) => a == b)

def groupBy[A](input: List[A])(fun: (A, A) => Boolean): List[List[A]] = input match {
  case Nil => Nil
  case (x::xs) =>
    val (ys, zs) = span(fun.curried(x), xs)
    (x::ys)::groupBy(zs)(fun)
}    
Run Code Online (Sandbox Code Playgroud)