我有以下代码,它们对List中的每个元素进行递归操作
def doMatch(list: List[Int]): Unit = list match {
case last :: Nil => println("Final element.")
case head :: tail => println("Recursing..."); doMatch(tail)
}
Run Code Online (Sandbox Code Playgroud)
现在,忽略通过filter()和foreach()可以使用此功能,这可以正常工作.但是,如果我尝试将其更改为接受任何Seq [Int],我会遇到问题:
以下是我认为代码的外观,除非它不起作用:
def doMatch(seq: Seq[Int]): Unit = seq match {
case last +: Seq() => println("Final element.")
case head +: tail => println("Recursing..."); doMatch(tail)
}
Run Code Online (Sandbox Code Playgroud)
编辑:这么多好的答案!我接受了agilesteel的答案,因为他是第一个注意到::在我的例子中不是运算符,而是一个案例类,因此差异.
val x = for(i <- 1 to 3) yield i
x match {
case 1 :: rest => ... // compile error
}
Run Code Online (Sandbox Code Playgroud)
构造函数无法实例化为期望的类型; found:collection.immutable.::: [B] required:scala.collection.immutable.IndexedSeq [Int]
当匹配收到IndexedSeq而不是LinearSeq时,这与MatchError的问题相同.
问题是,怎么做对了?.toList到处添加似乎不对.并创建一个自己的提取器来处理每一个Seq(如另一个问题的答案所述)如果每个人都这样做会导致一团糟......
我想问题是,为什么我不能影响序列理解的返回类型,或者:为什么不是Seq标准库的这种通用提取器部分?