Scala - iterators and takeWhile -
i running following piece of code:
val = list(1,1,1,2,2,3,3).iterator.buffered val compare = it.head it.takewhile(_ == compare).tolist and returns (1,1,1). however, if run as:
val = list(1,1,1,2,2,3,3).iterator.buffered it.takewhile(_ == it.head).tolist i getting (1,1). why case? isn't head evaluated upon calling takewhile , result should same?
because iterator mutable, value of it.head depends on when evaluated.
inspecting implementation of takewhile reveals removes head of iterator before applying predicate.
so, on third iteration, it.head evaluated within predicate 2, because third element has been removed.
this illustration of why should prefer immutability. rules out whole class of non-obvious behaviour this.
Comments
Post a Comment