Applying @tailrec I’m getting error from scala compiler: “could not optimize @tailrec annotated method get: it contains a recursive call targetting a supertype case _ => tail.get(n-1)”. Could someone explain why is that?
trait List[T] {
def isEmpty: Boolean
def head: T
def tail: List[T]
def get(n: Int): T
}
class Cons[T](val head: T, val tail: List[T]) extends List[T]{
def isEmpty = false
@tailrec
final def get(n: Int) =
n match {
case 0 => head
case _ => tail.get(n-1)
}
}
class Nil[T] extends List[T]{
def isEmpty = true
def head = throw new NoSuchElementException("Nil.head")
def tail = throw new NoSuchElementException("Nil.tail")
final def get(n: Int): T = throw new IndexOutOfBoundsException
}
object Main extends App{
println(new Cons(4, new Cons(7, new Cons(13, new Nil))).get(3))
}
Try to imagine what’s happening here and what you’re asking the compiler to do. Tail call optimization, roughly, turns the method call into a loop, taking the arguments of the method and turning them into variables that are reassigned at each iteration of the loop.
Here, there are two such “loop variables”:
nand the list cell itself on which thegetmethod is called, which is actuallythisin the method body. The next value fornis fine: it’sn - 1and also anInt. The next value for the list cell, which istail, is a problem, however:thishas typeCons[T], buttailonly has typeList[T].Thus, there is no way the compiler can turn it into a loop, as there is no guarantee that
tailis aCons[T]— and sure enough, at the end of the list, it is aNil.One way to “fix” it would be:
(Works if both
ConsandNilare case classes — but you’ll probably want to makeNilacase objectandList[T]covariant inT.)