看看Scala 2.10.0
在LinearSeqOptimized.scala
中对LinearSeqOptimized#find
的实现,为什么需要调用var这些=这个
?
为什么不能简单地使用这个?
override /*IterableLike*/
def find(p: A => Boolean): Option[A] = {
var these = this
while (!these.isEmpty) {
if (p(these.head)) return Some(these.head)
these = these.tail
}
None
}
最佳答案
因为您必须在循环外具有相同的条件和操作,然后开始使用它们。
将每个人放在同一个篮子中并在循环中完成所有操作要简单得多。示例:
def find(p: A => Boolean): Option[A] = {
if (!this.isEmpty && p(this.head)) {
return Some(this.head)
}
var these = this.tail
while (!these.isEmpty) {
if (p(these.head)) return Some(these.head)
these = these.tail
}
None
}
如您所见,不太聪明。
您还可以轻松地将其实现为 @tailrec
操作:
@tailrec final def find[A](p : A => Boolean) : Option[A] = {
if ( this.isEmpty ) {
None
} else {
if ( p(this.head) ) {
Some(this.head)
} else {
this.tail.find(p)
}
}
}
在 Scala 中并不是这样完成的,因为 tailrec 调用必须是最终的或私有(private)的。
关于algorithm - LinearSeqOptimized#查找引用副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20408487/