Scala tail recursive optimization, reuse function Stack

Source: Internet
Author: User
In Scala, if a function calls itself in the last step (you must call yourself completely, but you cannot add additional operators), the function stack will be reused in Scala, in this way, recursive calls are converted into linear calls, greatly improving the efficiency.
If a function callitself as its last action, the function's stack frame can be reused. This is called tail recursion.
=> Tail recursive functions are iterative process

Two versions of factorial functions are implemented here. One is a common method, and the other is a tail recursive optimization.
/*In Scala, only directly recursive call to the current function are optimized.One can require that a function is tail-recursive using a @tailrec annotation:   @tailrec   def gcd(a: Int, b: Int): Int = ...If the annotation is given, and the implementation of gcd were nottail recursive, an error would be issued.*/import scala.annotation.tailrecobject exercise {  def factorial(n: Int): Int =    if (n == 0) 1 else n * factorial(n-1)  //a tail recursive version of factorial  def factorialTailRecursion(n: Int): Int = {    @tailrec    def loop(acc: Int, n: Int): Int =      if (n == 0) acc      else loop(acc * n, n-1)      loop(1, n)  }  factorial(4)  factorialTailRecursion(4) //optimized! the function‘s stack frame can be reused!}

 

Scala tail recursive optimization, reuse function Stack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.