Scala does optimize tail recursion at compile time

I just got wowed. Scala does optimize tail recursion at compile time, I didn’t know that.

Say I have the following countDown() method —

public static void main(String[] args) {
    countDown(1_000_000_000);
}


public static void countDown(int n) {
    if (n == 0) return;
    System.out.println(n + " ...");

    waitASecond();

    countDown(n - 1);
}

private static void waitASecond() {
    // do  some bla bla
}

Run it, you will immediately get java.lang.StackOverflowError. The equivalent Scala code, however, would run just fine.


def main(args: Array[String]): Unit = {
  countDown(1000000000)
}

def waitASecond() = {}

def countDown(n: Int): Unit = {
  if (n == 0) return
  else {
    println(n + " ...")
    waitASecond()
    countDown(n - 1)
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s