Why is a function not recursive?

I read the Program at Scala M. Odersky, and he says that

Functions such as approximate ones, which call themselves the last action, are called tail recursive.

So, I tried this:

object Main extends App {
    implicit val mc = new MyClass(8)
    val ti = new TestImplct
    ti.test
}

class TestImplct {
  def test(implicit mc : MyClass): Unit = {
    println(mc.i)
    mc.i -= 1
    if(mc.i < 0){
      throw new IllegalArgumentException
    }
    test
  }
}

class MyClass(var i : Int)

IDEONE DEMO

But it generates the next stack trace

 Exception in thread "main" java.lang.IllegalArgumentException
    at TestImplct.test(Main.scala:13)
    at TestImplct.test(Main.scala:15)
    at TestImplct.test(Main.scala:15)
    at TestImplct.test(Main.scala:15)
    at TestImplct.test(Main.scala:15)
    at TestImplct.test(Main.scala:15)
    at TestImplct.test(Main.scala:15)
    at TestImplct.test(Main.scala:15)
    at TestImplct.test(Main.scala:15)

This means that it generates a new stack stack for each recursive call. But the last action is to call yourself. What is wrong and how to make tail-recursive?

Why doesn't the compiler perform tail call optimization?

+4
source share
2 answers

@tailrec . , , , :

Main.scala: 12: : @tailrec annotated method: , ,

, final, .

+9

. mc . .

Boolean, , false, < 0, true.

, @tailrec, .

+2

Source: https://habr.com/ru/post/1652973/


All Articles