以斐波那契数列的计算函数为例, 实践 Scala 中尾递归函数的编写
object Test extends App {
def fib(n: Int): Int = {
@annotation.tailrec
def fib_iter(f0: Int, f1: Int, cnt: Int): Int =
if (cnt <= 0) f0
else fib_iter(f1, f0+f1, cnt-1)
fib_iter(0, 1, n)
}
(0 until 10).foreach { n => println(fib(n)) }
}
原文地址:https://www.cnblogs.com/wander4096/p/9164222.html
时间: 2024-10-08 23:40:45