Process7 Process7 - 1 month ago 15
Scala Question

Scala equivalent of python itertools 'cycle'

Is there an equivalent of python's itertools.cycle()?

I would like to take a list of arrays and endlessly cycle them. So, if the arrays are named A through D, itertools.cycle can do:

itertools.cycle('[A,B,C,D]') --> A B C D A B C D...


This 'cycles' or 'rolls' the original collection.

I am digging into Scala streams in order to answer this question, but I thought I would ask to see if I am missing some built-in functionality.

Thanks!

Answer

Iterator.continually will do the trick

 Iterator.continually("scala").flatMap(x => x)

Scala REPL

scala> Iterator.continually("scala").flatMap(x => x).take(100).foreach(println)

Or

Yes you can use Stream to model this

def cycle(str: String): Stream[String] = str #:: cycle(str)

usage:

cycle("scala").flatten

Scala REPL

scala> def cycle(str: String): Stream[String] = str #:: cycle(str)
cycle: (str: String)Stream[String]

scala> cycle("java").take(100)
res2: scala.collection.immutable.Stream[String] = Stream(java, ?)

scala> cycle("java").take(100).force
res3: scala.collection.immutable.Stream[String] = Stream(java, java, java, java, java, java, ... )
Comments