【发布时间】:2016-03-01 02:05:02
【问题描述】:
在练习 scala 时,我正在尝试使用模式匹配对整数列表进行插入排序。以前,打印列表的以下代码工作得非常好:
object PrintList {
def iPrint(xs: List[Int]):Unit = xs match {
case x :: ys => {
print(x+" -> ")
iPrint(ys)
}
case _ => println("Nil")
}
def main(args: Array[String]) {
//val l = Nil.::(1).::(2).::(3).::(4)
val l = 4 :: 3 :: 2 :: 1 :: Nil
iPrint(l)
}
}
但是,以下用于对列表进行排序的代码无法编译:
def insert(x : Int, l1 : List[Int]):List = {
//stubbed
List()
}
def iSort(l : List[Int]):List = l match {
case x :: ys => insert(x , iSort(ys))
case Nil => Nil
}
我在这里错过了什么非常琐碎的事情吗??
编辑: 修改代码如下:
def insert(x : Int , l1 : List[Int]):List[Int] = {
//stubbed
List(0)
}
def iSort(l : List[Int]):List[Int] = l match {
case (x:Int) :: (ys:List[Int]) => insert(x , iSort(ys))
case _ => List(0)
}
在第一个 case 语句中仍然出现错误 - Pattern type is incompatible with expected type. Found: ::[B], expected: List[Int]
将 Intellij Idea 与 Scala 插件一起使用 - 2.11.7。
【问题讨论】:
-
您可能想要添加编译器错误。我不明白。
insert采用什么参数?因为它看起来只需要一个List参数,但您使用 2 个参数调用它。 -
您可能需要指定返回列表的类型:List[Int],而且您的插入方法只需要一个参数,而不是两个。
-
正如@hasumedic 指出的那样,您还需要为返回的
List...指定一个类型参数...List[Int]这样您的函数就变成了def iSort(l : List[Int]): List[Int]... -
我在最初的问题中犯了一个错误,插入函数有两个参数:一个整数和一个列表。相应地进行了更改。但是,我仍然遇到同样的错误。尝试了所有提到类型参数的排列,仍然无法编译。以下是错误:
Pattern type is incompatible with expected type. found::[B], required List[Int]。 - 即使在将类型参数添加到 List 声明并将 case 语句修改为case (x:Int) :: (ys:List[Int]) => insert(iSort(ys))之后。我正在使用带有 scala 插件的 intellij。 -
看起来像 intellij 中的一个错误。尝试执行scala repl中的代码