swift - Behaviour of lazy dropLast -


i'm trying figure out behaviour of droplast when evaluated lazily (questions in bold):

var iterationcount = 0  let sequence = [1, 1, 1].lazy.flatmap { (element: int) -> [int] in   iterationcount += 1   return [element, 2] }.droplast()  print(iterationcount) // 18  _ = sequence.foreach{_ in}  print(iterationcount) // 30 

shouldn't first call print show 0 , second call print show 3 since it's lazy? shows 18 , 30example.

var iterationcount = 0  let sequence = [1, 1, 1].lazy.flatmap { (element: int) -> [int] in   iterationcount += 1   return [element, 2] }  print(iterationcount) // 0  _ = sequence.foreach{_ in}  print(iterationcount) // 3 

when remove call droplast works expectedexample. is droplast culprit here?

var iterationcount = 0  let sequence = [1, 1, 1].lazy.map { (element: int) -> [int] in   iterationcount += 1   return [element, 2] }.droplast()  print(iterationcount) // 0  _ = sequence.foreach{_ in}  print(iterationcount) // 2 

but wait, there more. map, droplast works expectedexample.

why this?


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -