Scala - 递归函数



递归在纯函数式编程中扮演着重要的角色,Scala 非常好的支持递归函数。递归意味着一个函数可以重复调用自身。

尝试以下程序,这是一个很好的递归示例,其中计算了传递数字的阶乘。

示例

object Demo {
   def main(args: Array[String]) {
      for (i <- 1 to 10)
         println( "Factorial of " + i + ": = " + factorial(i) )
   }
   
   def factorial(n: BigInt): BigInt = {  
      if (n <= 1)
         1  
      else    
      n * factorial(n - 1)
   }
}

将上述程序保存在 **Demo.scala** 中。以下命令用于编译和执行此程序。

命令

\>scalac Demo.scala
\>scala Demo

输出

Factorial of 1: = 1
Factorial of 2: = 2
Factorial of 3: = 6
Factorial of 4: = 24
Factorial of 5: = 120
Factorial of 6: = 720
Factorial of 7: = 5040
Factorial of 8: = 40320
Factorial of 9: = 362880
Factorial of 10: = 3628800
scala_functions.htm
广告