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

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -