Scala recursive function

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
  1. package test_first
  2. object tailrec extendsApp{
  3. @annotation.tailrec
  4. def factorial(n:Int,m:Int):Int=
  5. if(n<=0) m
  6. else factorial(n-1,m*n)
  7. println(factorial(5,1))
  8. }
 
Four running results
120

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326988095&siteId=291194637