如果我的理解是正確的,你正試圖以2乘以每個元素列表,看看這個:
$ scala
Welcome to Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_05).
Type in expressions to have them evaluated.
Type :help for more information.
scala> @scala.annotation.tailrec
| def sampleTailRec(list: List[Int], accumulator: List[Int] = List.empty[Int]) : List[Int] = {
| list match {
| case Nil => accumulator.reverse
| case head :: Nil => sampleTailRec(Nil, head * 2 :: accumulator)
| case head :: tail => sampleTailRec(tail, head * 2 :: accumulator)
| }
| }
sampleTailRec: (list: List[Int], accumulator: List[Int])List[Int]
scala> sampleTailRec(1 to 10 toList)
warning: there were 1 feature warning(s); re-run with -feature for details
res0: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
感謝Jesper的分解。它幫助我理解爲什麼我的方法不是尾遞歸。 –