我在斯卡拉寫了這樣的功能:斯卡拉尾遞歸優化
def isSorted[T](list : List[T])(compare : (T, T) => Boolean) : Boolean = {
list match {
case Nil => true
case x :: Nil => true
case x :: rest => !compare(rest.head, x) && isSorted(rest)(compare)
}
}
我很好奇的編譯器是否優化掉的遞歸調用。遞歸調用只有發生,如果領先的比較成功。如果沒有,是否有辦法提前爆炸並仍然實現尾部遞歸優化?
這就是['@ annotation.tailrec'](http://stackoverflow.com/questions/3114142/what-is-the-scala-註釋到確保尾巴遞歸功能被優化)用於 – 2013-03-19 15:20:23
酷。它似乎被優化。謝謝! – 2013-03-19 15:25:18
需要說明的是,'@ tailrec'不會奇蹟般地使該方法成爲尾遞歸,這使得它不是尾遞歸的錯誤。 – 2013-03-19 15:54:31