Scala-迭代器和takeWhile
我正在运行以下代码:Scala-迭代器和takeWhile,scala,iterator,Scala,Iterator,我正在运行以下代码: val it = List(1,1,1,2,2,3,3).iterator.buffered val compare = it.head it.takeWhile(_ == compare).toList 它返回(1,1,1)。但是,如果我以以下方式运行此操作: val it = List(1,1,1,2,2,3,3).iterator.buffered it.takeWhile(_ == it.head).toList 我得到(1,1)。为什么会这样?调用take
val it = List(1,1,1,2,2,3,3).iterator.buffered
val compare = it.head
it.takeWhile(_ == compare).toList
它返回(1,1,1)。但是,如果我以以下方式运行此操作:
val it = List(1,1,1,2,2,3,3).iterator.buffered
it.takeWhile(_ == it.head).toList
我得到(1,1)。为什么会这样?调用
takeWhile
时不是对head
进行了评估,结果应该是相同的吗 因为迭代器是可变的,it.head的值取决于计算它的时间
检查发现它在应用谓词之前删除了迭代器的头部
因此,在第三次迭代中,从谓词中计算的it.head
将是2
,因为第三个元素已经被删除
这说明了为什么您更喜欢不变性。它排除了像这样一整类不明显的行为。添加到上面的@Ben James answer。以下是takeWhile
方法代码(学分:ben):
在第2行之后的第三次迭代中,值是:hd=1
,剩余的迭代器是List(2,2,3,3)
。调用p(hd)
时,它会检查迭代器的头
,在本例中是2
。因此它破裂了
def hasNext = hdDefined || tail.hasNext && {
hd = tail.next() //line 2
if (p(hd)) hdDefined = true
else tail = Iterator.empty
hdDefined
}