Scala recursive function
Recursive function plays an important role in functional programming languages.
Scala also supports recursive functions.
Recursive function means that the function can call itself.
The above example uses a recursive function to compute factorial:
object Test { def main(args: Array[String]) { for (i <- 1 to 10) println(i + " 的阶乘为: = " + factorial(i) ) } def factorial(n: BigInt): BigInt = { if (n <= 1) 1 else n * factorial(n - 1) } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test 1 的阶乘为: = 1 2 的阶乘为: = 2 3 的阶乘为: = 6 4 的阶乘为: = 24 5 的阶乘为: = 120 6 的阶乘为: = 720 7 的阶乘为: = 5040 8 的阶乘为: = 40320 9 的阶乘为: = 362880 10 的阶乘为: = 3628800