当前位置: 动力学知识库 > 问答 > 编程问答 >

scala - Recursive call not in tail position

问题描述:

Say I define the following function:

final def myFunc[T](list: List[T]): List[T] = list match {

case h :: t =>

h :: myFunc(t)

case _ =>

Nil

}

When I add a tailrec annotation the compiler gives me the following error:

could not optimize @tailrec annotated method myFunc: it contains a

recursive call not in tail position: ^Nil.

I am confused as to how the declaration of Nil can be a recursive call?

网友答案:

The problem is not with the Nil but with h :: myFunc(t) because myFunc(t) is not the last call. The last call is to the operator :: on the result of myFunc(t). That is why the function is not tail recursive.

分享给朋友:
您可能感兴趣的文章:
随机阅读: