Splitting an iterator in scala 2.7.5

It looks like there is no partition

method on Iterator

in scala 2.7.5 (there is in 2.8). I would like to have a partition without losing laziness Iterator

, so the next option is not :

itr.toList.partition( someTest(_) )

      

Can anyone recommend a way to do this without implementing my own method partition

? For example, is there a way to convert Iterator

to lazy-evaluable Stream

?

+2


source to share


1 answer


Have you tried the method Stream.fromIterator

? It creates a stream containing the elements of the given iterator :).

Example:

val iter = List(1,2,3,4).elements // just a simple iterator

val str = Stream.fromIterator(iter)

str.partition(_ >= 3)

      

Hope this helps (and this is what you meant).



EDIT: Just an example to show that this is lazy (and memoised - like everyone else Stream

).

scala> val iter = new Iterator[Int] {
     | var lst = List(1,2,3,4)
     | def hasNext() = !lst.isEmpty
     | def next() = { val x = lst.head; println(x); lst = lst.tail; x }
     | }

scala> val stream = Stream.fromIterator(iter)
1
stream: Stream[Int] = Stream(1, ?)

scala> stream.partition(_ >= 2)
2
3
4
res1: (Iterable[Int], Iterable[Int]) = (ArrayBuffer(2, 3, 4),ArrayBuffer(1))

scala> stream.partition(_ >= 3)
res2: (Iterable[Int], Iterable[Int]) = (ArrayBuffer(3, 4),ArrayBuffer(1, 2))

      

NB: left some way out as it was quite verbose.

- Flavi Chipchigan

+8


source







All Articles