错误:@tailrec annotated方法不包含递归调用

时间:2013-08-25 09:02:20

标签: scala recursion

运行这段代码时:

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中,我收到以下错误:

阶> :9:错误:@tailrec annotated方法不包含递归调用

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

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

1 个答案:

答案 0 :(得分:4)

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)
    }
}