使用模式匹配确定列表的 lat 元素的代码:
@tailrec
def last_rec[A](list : List[A]) : A = {
list match {
case (x :: Nil) => x
case (_ :: xs) => last_rec(xs)
case Nil => throw new NoSuchElementException
}
}
我想编译代码,我被编译器“大喊大叫”:
PS D:\workspace\scala\P99> scalac .\P01.scala
.\P01.scala:18: error: could not optimize @tailrec annotated method last2: it contains a recursive call not in tail position
case Nil => throw new NoSuchElementException
^
one error found
如果我删除 @tailrec 注释 - 代码编译。如何修改代码以进行尾部记录优化?