Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive call not in tail position

Tags:

scala

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?

like image 368
user79074 Avatar asked May 28 '15 14:05

user79074


1 Answers

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.

like image 108
Gregor Raýman Avatar answered Oct 22 '22 02:10

Gregor Raýman