0

运行这段代码时:

object P01 {
    @annotation.tailrec
    final def lastRecursive[A] (ls:List[A]):A = {
        def lr[A] (l:List[A]):A = l match {
            case h :: Nil  => h
            case _ :: tail => lr(tail)
            case _         => throw new NoSuchElementException  
        }
        lr(ls)
    }
}

P01.lastRecursive(List(1,2,3))

,在 scala 2.10.2 REPL 中,我收到以下错误:

scala> :9: 错误:@tailrec 注释方法不包含递归调用

    final def lastRecursive[A] (ls:List[A]):A = {
              ^

请帮忙,我不明白我做错了什么。

4

1 回答 1

5

lastRecursive 不是尾递归,但 lr 是。这对我有用:

object P01 {
    final def lastRecursive[A] (ls:List[A]):A = {
        @annotation.tailrec
        def lr[A] (l:List[A]):A = l match {
            case h :: Nil  => h
            case _ :: tail => lr(tail)
            case _         => throw new NoSuchElementException  
        }
        lr(ls)
    }
}
于 2013-08-25T09:09:16.497 回答