Partizionamento un Iterator in scala 2.7.5
-
19-09-2019 - |
Domanda
Sembra come se non esiste un metodo partition
su un Iterator
in scala 2.7.5 (c'è in 2.8). Mi piacerebbe avere una partizione senza perdere il pigrizia del Iterator
, in modo che la segue è non un'opzione:
itr.toList.partition( someTest(_) )
Qualcuno può raccomandare un modo di fare questo senza implementare il mio metodo partition
? Per esempio, c'è un modo di trasformare una Iterator
in un Stream
pigramente-valutato?
Soluzione
Hai provato la metodo Stream.fromIterator
? Si produce una corrente contenente gli elementi della proposta iteratore:.)
Un esempio potrebbe essere:
val iter = List(1,2,3,4).elements // just a simple iterator
val str = Stream.fromIterator(iter)
str.partition(_ >= 3)
Speranza che aiuta (ed è la cosa che aveva in mente).
EDIT:. Solo un esempio per dimostrare che questo è pigro (e memoised - come tutte le Stream
s sono)
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:. Lasciato qualche uscita fuori come era piuttosto prolissa
- Flaviu Cipcigan