Scala Recursive Functions
Recursive functions play an important role in functional programming languages.
Scala also supports recursive functions.
A recursive function means a function can call itself.
The above example uses a recursive function to calculate the 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)
}
}
Executing the above code produces the following output:
$ scalac Test.scala $ scala Test 1 的阶乘为: = 1 2 的阶乘为: = 2 3 的阶乘为: = 6 4 的阶乘为: = 24 5 的阶乘为: = 120 6 的阶乘为: = 720 7 的阶乘为: = 5040 8 的阶乘为: = 40320 9 的阶乘为: = 362880 10 的阶乘为: = 3628800Other Extensions
Scala Functions