Scala Learning (3): Tail recursion definition

Source: Internet
Author: User

For tail recursion, use Scala's two examples to illustrate the definition and simple implementation of tail recursion.

Example comparison

The function of seeking greatest common divisor

def gcd(a: Int, b: Int): Int =  if0else gcd(b, a % b)

The computed expansion is tail-recursive,

gcd -, +),if( +==0) - Elsegcd +, -% +),if(false) - Elsegcd +, -% +), GCD ( +, -% +), GCD ( +, -),if( -==0) + Elsegcd -, +% -), GCD ( -,7), GCD (7,0),if(0==0)7 Elsegcd0,7%0),7

function to find factorial

def factorial(n: Int): Int =  if01else1)

The computed expansion is non-tail recursive,

Factorial (4),if(4==0)1 Else 4* Factorial (4-1),4* Factorial (3),4* (3* Factorial (2)),4* (3* (2* Factorial (1)))4* (3* (2* (1* Factorial (0)))4* (3* (2* (1*1))) -
Tail recursion definition

A simple refinement of the definition:

If a function calls itself as its last action, the function's stack frame can be reused. This is called tail recursion.

The gcd function calls itself after the Else branch, and the factorial function, in the Else branch, is also multiplied by N when it calls itself, so it is not a tail recursion.

Rewrite

In the factorial function, write a function that receives n and the accumulated product value, which can become the tail recursion.

def factorial(n: Int): Int = {  def tailIter(product: Int, n: Int): Int = {    if0) product    else tailIter(product*n, n-1)  }  tailIter(1, n)}

Complete the full text:)

Scala Learning (3): Tail recursion definition

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.