缺少参数类型 [英] Missing parameter type

查看:50
本文介绍了缺少参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was rewriting a series of Haskell functions in Scala, and ran into a compilation error that I can't seem to explain

错误如下:

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)
                                                           ^

代码如下:

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
}

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

I'm not at all sure what's going on here, why it's complaining about a missing parameter type. As far as I can see everything is defined

推荐答案

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

It will compile if you provide an explicit generic type argument at the groupBy call site:

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

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

See this post for an explanation of why Scala's type inference is failing for this case.

如果你用柯里化的参数列表编写 groupBy 类型信息应该正确推断:

If you write groupBy with curried argument lists the type information should be inferred correctly:

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)
}    

这篇关于缺少参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆