In Scala, how to work with TraversableLike.toIterator inefficient intermediate stream

( Gen) is TraversableOnce.toIteratorredefined in TraversableLikelike toStream.iterator, causing the appearance of an intermediate stream.

As a simple example, let's say I'm trying to implement a simple utility izipthat always resorts its arguments to iterators before the call zipto get an efficient iterator over both collections.

The following is inefficiency (due to intermediate flow):

def izip[A,B](xs: TraversableOnce[A], ys: TraversableOnce[B]) =
  xs.toIterator zip ys.toIterator

and should be expanded to:

def izip[A,B](xs: Iterable[A], ys: Iterable[B]) =
  xs.iterator zip ys.iterator
def izip[A,B](xs: Iterator[A], ys: Iterable[B]) =
  xs zip ys.iterator
def izip[A,B](xs: Iterable[A], ys: Iterator[B]) =
  xs.iterator zip ys
def izip[A,B](xs: Iterator[A], ys: Iterator[B]) =
  xs zip ys
// .. and more needed to handle Traversables as well

Is there a better way?

+5
source share
1 answer

, , . , .

, TraversableLike toIterator, .

, , . , toIterator .

+2

All Articles