2013-03-29 27 views
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) 
    } 
} 
+0

可能的重複[什麼是斯卡拉註釋,以確保尾部遞歸函數優化?](http://stackoverflow.com/questions/3114142/what-is-the-scala-annotation-to-ensure-a -tail遞歸函數-被優化) –

回答

4

添加@tailrec之前函數定義,使編譯器產生的非tailrecursive方法是錯誤的:) 此外,你必須承擔的功能將高效作爲當務之急循環(亦稱爲/ while循環),當你用編譯器以這種方式優化它時。