【发布时间】:2011-12-10 23:16:30
【问题描述】:
我们在 Scala 中试验并行集合,并想检查结果是否有序。为此,我在 REPL 上编写了一个小函数来检查我们正在生成的非常大的 List:
def isOrdered(l:List[Int]):Boolean = { l match {
case Nil => true
case x::Nil => true
case x::y::Nil => x>y
case x::y::tail => x>y & isOrdered(tail)
}
}
它因 stackOverflow 而失败(这里的问题多么合适!)。 我期待它是尾部优化的。怎么了?
【问题讨论】:
-
实际上,如果头部元素大于下面的元素,这将产生
true,等等。就像在 3,2,1 中一样。 -
与您的问题没有直接关系,但请注意您的
case x::y::Nil是多余的,而您的case x::y::tail是错误的(考虑List(3,2,9))。
标签: scala stack-overflow tail-recursion tail-call-optimization