我对 Scala 模式匹配中的 :+ 和 +: 运算符感到困惑。
我有以下函数,它应该返回列表中的最后一个值
object Solution {
def last[A](seq: Seq[A]) : A = seq match {
case head +: Nil => head
case head +: tail => last(tail)
}
def main(args: Array[String]) {
println("1: " + last(List(1, 2, 3, 4)))
}
}
但是我在运行代码时收到一些错误
error: not found: value +:
error: not found: value head
error: not found: value +:
error: not found: value tail
我在这里缺少什么?
编辑:我正在使用 Scala 2.9.2 运行它
最佳答案
提取器是对象,因此您需要查找+:
。
2.11,
scala> +:
res0: collection.+:.type = scala.collection.$plus$colon$@5f2050f6
但是比较一下
http://www.scala-lang.org/api/2.11.0/#scala.collection.$plus$colon$
与
http://www.scala-lang.org/api/2.9.2/#scala.collection.package
没有这样的提取器的地方。
关于Scala模式匹配:+ +: operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23399700/