我有以下代码,它对列表中的每个元素进行递归操作
def doMatch(list: List[Int]): Unit = list match {
case last :: Nil => println("Final element.")
case head :: tail => println("Recursing..."); doMatch(tail)
}
现在,忽略这个功能可以通过 filter() 和 foreach() 获得,这工作得很好。但是,如果我尝试更改它以接受任何 Seq[Int],我会遇到问题:
- Seq 没有::,但它有 +:,据我了解,这基本上是同一件事。但是,如果我尝试在 head +: tail 上匹配,编译器会提示“错误:未找到:值+:”
- Nil 是 List 特有的,我不知道用什么来替换它。如果我解决了上一个问题,我将尝试 Seq()
我认为代码应该是这样的,但它不起作用:
def doMatch(seq: Seq[Int]): Unit = seq match {
case last +: Seq() => println("Final element.")
case head +: tail => println("Recursing..."); doMatch(tail)
}
编辑:这么多好的答案!我接受agilesteel的答案,因为他是第一个指出::在我的示例中不是运算符,而是案例类,因此存在差异的答案。
最佳答案
截至 2012 年 3 月的 IDE,这适用于 2.10+:
def doMatch(seq: Seq[Int]): Unit = seq match {
case last +: Seq() => println("Final element.")
case head +: tail => println("Recursing..."); doMatch(tail)
} //> doMatch: (seq: Seq[Int])Unit
doMatch(List(1, 2)) //> Recursing...
//| Final element.
更一般地说,为 SeqExtractors 中的 Seq
添加了两个不同的 head/tail 和 init/last 分解对象,镜像附加/前置。 :
List(1, 2) match { case init :+ last => last } //> res0: Int = 2
List(1, 2) match { case head +: tail => tail } //> res1: List[Int] = List(2)
Vector(1, 2) match { case init :+ last => last } //> res2: Int = 2
Vector(1, 2) match { case head +: tail => tail } //> res3: scala.collection.immutable.Vector[Int] = Vector(2)
关于除列表之外的序列上的 Scala 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6807540/