Scala - 迭代器和 takeWhile
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16356897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala - iterators and takeWhile
提问by Bober02
I am running the following piece of code:
我正在运行以下代码:
val it = List(1,1,1,2,2,3,3).iterator.buffered
val compare = it.head
it.takeWhile(_ == compare).toList
and it returns (1,1,1). However, if I run this as:
它返回 (1,1,1)。但是,如果我将其运行为:
val it = List(1,1,1,2,2,3,3).iterator.buffered
it.takeWhile(_ == it.head).toList
I am getting (1,1). Why is this the case? Isn't headevaluated upon calling takeWhileand the result should be the same?
我得到(1,1)。为什么会这样?不是head在调用时进行评估,takeWhile结果应该是一样的吗?
回答by Ben James
Because the iterator is mutable, the value of it.headdepends on when it is evaluated.
因为迭代器是可变的, 的值it.head取决于它的评估时间。
Inspecting the implementation of takeWhilereveals that it removes the head of the iterator beforeapplying the predicate.
检查 的实现takeWhile表明它在应用谓词之前删除了迭代器的头部。
So, on the third iteration, it.headevaluated from within the predicate will be 2, because the third element has already been removed.
因此,在第三次迭代中,it.head从谓词内部评估将是2,因为第三个元素已被删除。
This is an illustration of why you should prefer immutability. It rules out a whole class of non-obvious behaviour like this.
这说明了为什么您应该更喜欢不变性。它排除了像这样的一整类不明显的行为。
回答by Jatin
Adding to @Ben James answer above. Below is takeWhilemethod code (credits: ben):
添加到上面的@Ben James 答案。以下是takeWhile方法代码(来源:ben):
def hasNext = hdDefined || tail.hasNext && {
hd = tail.next() //line 2
if (p(hd)) hdDefined = true
else tail = Iterator.empty
hdDefined
}
In the third iteration after line 2, the value is: hd=1and remaining Iterator is List(2,2,3,3). on calling p(hd), it checks the iterator's headwhich in this case is 2. Hence it breaks.
在第 2 行之后的第三次迭代中,值为:hd=1,剩余的迭代器为List(2,2,3,3)。在调用 时p(hd),它会检查迭代器head,在这种情况下是2。因此它打破了。

![scala 我怎样才能扁平化这个 Future[T] 结构?](/res/img/loading.gif)