在下面的代码中 - 列表的最大值和总和非常微不足道 - 我有一个在方法末尾调用的递归函数。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)
}
}