【问题标题】:error: @tailrec annotated method contains no recursive calls错误:@tailrec 注释方法不包含递归调用
【发布时间】:2013-08-25 17:09:16
【问题描述】:

运行这段代码时:

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 = {
              ^

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

【问题讨论】:

  • 您似乎打算将注释放在lr 而不是lastRecursive

标签: scala recursion


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多