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