位置:首頁 > 高級語言 > Scala教學 > Scala遞歸函數

Scala遞歸函數

遞歸起著純粹函數式編程很大的作用,Scala支持遞歸功能非常好。遞歸是指的函數可以反複調用自身。以下是遞歸,用於計算階乘數的一個很好的例子:

object Test {
   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)
   }
}

當上述代碼被編譯和執行時,它產生了以下結果:

C:/>scalac Test.scala
C:/>scala Test
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

C:/>