Iterators for mutable collections in Scala?
Asked Answered
S

2

6

I just found out that there are such iterators in Java.
Does Scala have iterators with 'set' and 'remove' methods for iterating (and modifying) mutable collections like array?
If there is no such iterator then is there a good reason for that?

Schooner answered 10/5, 2010 at 13:52 Comment(2)
You should copy (or paraphrase) the answer(s) you got on the mailing list over here (for posterity).Peptize
@Randall. Ok, I gave the link to maximize usefulness.Marjorie
H
6

Scala does not currently have such an iterator.

I suspect that it does not because

  • Such iterators are not general (i.e they are only usable with mutable collections) but consume namespace.

  • Because they can rapidly become confusing to think about in conjunction with lazy operations like takeWhile (Is it always obvious what x.takeWhile(_<5).add(5) should do? On the one hand, the order of operations seems like you should take first, and then add; but on the other, take is lazy while add can often be implemented immediately, so combining them this way would be dangerous naively.)

  • Such iterators are only a good idea algorithmically with a very specialized set of collections (basically only linked lists and trees; add and remove is foolish to use on arrays anyway, and it doesn't make much sense on sets).

  • When an intrinsic conflict arises between generality and speed, the Scala collections library typically favors generality. This sort of iterator makes you think about the collections in a more particular way (i.e. more closely tied to the underlying data structure). You could imagine a library that made different choices, but for a maximally useful (and still quite performant) library, the Scala collections library philosophy is probably the better way to go.

Hopefully answered 10/5, 2010 at 19:40 Comment(1)
Very good arguments, thank you. I don't see a danger with takeWhile. It is like x = x+1. Maybe some collections should provide specialized iterators mixed from several traits? Or mebye some kind of reference should returned like here: #2799628Marjorie
S
1

Thread on the same topic on comp.lang.scala.user

Schooner answered 11/5, 2010 at 0:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.