a recursive function
A technique for implementing loops in functional programming.
Example: Calculate n!
def factorial (n:Int):Int =
if (n<=0) 1
else n * factorial(n-1)
Two-tail recursive function
All recursive forms of calls in a tail-recursive function occur at the end of the function.
When the compiler detects that a function call is tail recursive, it overwrites the current active record instead of creating a new one on the stack.
three code
package test_first
object tailrec extendsApp{
@annotation.tailrec
def factorial(n:Int,m:Int):Int=
if(n<=0) m
else factorial(n-1,m*n)
println(factorial(5,1))
}
Four running results
120