1
在下面的代碼中 - 相當微不足道的最大值和列表總和 - 我在方法的末尾調用了遞歸函數。 scala編譯器會將它視爲尾遞歸併優化堆棧幀使用情況嗎?我如何知道/我該如何驗證?尾遞歸 - 這將使幀的最佳使用,以及如何檢查編譯爲尾遞歸?
package example
import common._
object Lists {
def sum(xs: List[Int]): Int = {
def recSum(current: Int, remaining: List[Int]): Int = {
if (remaining.isEmpty) current else recSum(current + remaining.head, remaining.drop(1))
}
recSum(0, xs)
}
def max(xs: List[Int]): Int = {
def recMax(current: Int, remaining: List[Int], firstIteration: Boolean): Int = {
if(remaining.isEmpty){
current
}else{
val newMax = if (firstIteration || remaining.head>current) remaining.head else current
recMax(newMax, remaining.drop(1), false)
}
}
if (xs.isEmpty) throw new NoSuchElementException else recMax(0, xs, true)
}
}
可能的重複[什麼是斯卡拉註釋,以確保尾部遞歸函數優化?](http://stackoverflow.com/questions/3114142/what-is-the-scala-annotation-to-ensure-a -tail遞歸函數-被優化) –