Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to use @tailrec in Scala?

In the following example of a Scala function:

@tailrec def someFunction( ... ): Unit = {

Is the @tailrec annotation doing anything useful or is it just nice to know that this is a tail recursion?

like image 716
JamboShrimp Avatar asked Nov 04 '13 09:11

JamboShrimp


People also ask

What does @tailrec do in Scala?

In Scala 2.8, you will also be able to use the new @tailrec annotation to get information about which methods are optimised. This annotation lets you mark specific methods that you hope the compiler will optimise. You will then get a warning if they are not optimised by the compiler.

How well does tail recursion work in Scala?

The tail recursive functions better than non tail recursive functions because tail-recursion can be optimized by compiler. A recursive function is said to be tail recursive if the recursive call is the last thing done by the function. There is no need to keep record of the previous state.

Does Scala have tail call optimization?

The nice thing about Scala is that tail recursive methods are automatically optimized to not allocate unnecessary stack frames.

What is recursion in Scala?

< Scala. Recursion refers to a general method that involves defining a solution or object in terms of itself. Recursive functions refer to a kind of function where the definition of a function includes calling the function itself.


2 Answers

@tailrec - will produce a compilation error if a tail call optimization cannot be performed by the compiler in the annotated method.

so yes it does do something ....

check out - http://blog.richdougherty.com/2009/04/tail-calls-tailrec-and-trampolines.html

like image 85
Nimrod007 Avatar answered Oct 06 '22 16:10

Nimrod007


Nimrod007' answer is sufficient, But I also like to add some points.

Adding @tailrec definitely clears a benefit of doubt in code. You IDE might detect function as tail recursive but Scala might not, This is why it is better to add @tailrec to the function.

You can refer the code below.

import scala.annotation.tailrec

object Application extends App {
  println("Hello World")
  val i = 60000
  //  val i = 1000

  GetSum().trueTailRecursion(i)
  println("\nCompleted")
  GetSum().maybeTrueTailRecursion(i)
}

case class GetSum() {

  def maybeTrueTailRecursion(i: Int): Int = {
    print(".")
    if(i==1) 1
    else maybeTrueTailRecursion(i - 1)
  }

  @tailrec
  final def trueTailRecursion(i: Int): Int = {
    print(".")
    if(i==1) 1
    else trueTailRecursion(i - 1)
  }

}

In the above example, trueTailRecursion will be able to print dotted line but maybeTrueTailRecursion will crash with StackOverFlowError. Although the function is same.

like image 41
shri Avatar answered Oct 06 '22 17:10

shri