Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala has smart compiler?

I made recursive function, just like

require : L (List[Int])

L pattern matching

  1. Nil => Thread.dumpStack()
  2. x :: xs => print(x) + function(xs)
def function(L : List[Int]) {
    L match {
        case Nil => Thread.dumpStack()
        case x :: xs => print(x + " "); function(xs)
    }
}

val l = (1 to 5).toList // function(l)

So I think this function in the stack frame n times, but it occurs one time, I think this function has already found Nil and print out exception Thread.dumpStack.

Is scala compiler smart or other else?

like image 221
Silvester Avatar asked Feb 23 '23 10:02

Silvester


1 Answers

You are observing tail recursion: there is nothing to store from one iteration to the next, so the recursion is essentially turned into a while loop by the compiler. (So, yes, the compiler is smart in that way.)

like image 102
Rex Kerr Avatar answered Mar 06 '23 07:03

Rex Kerr