split a stream in many

后端 未结 6 1593
清酒与你
清酒与你 2021-01-05 07:46

I\'d like to know if there a elegant way to achieve something like that:

val l = Stream.from(1)

val parts = l.some_function(3)  //any number

parts.foreach(         


        
6条回答
  •  清酒与你
    2021-01-05 08:22

    def roundRobin[T](n: Int, xs: Stream[T]) = {
      val groups = xs.grouped(n).map(_.toIndexedSeq).toStream
      (0 until n).map(i => groups.flatMap(_.lift(i)))
    }
    

    works in the infinite case:

    scala> roundRobin(3, Stream.from(0)).map(_.take(3).force.mkString).mkString(" ")
    res6: String = 036 147 258
    

    using flatMap/lift instead of plain map/apply means it works even if the input is finite and the length isn't a multiple of n:

    scala> roundRobin(3, Stream.from(0).take(10)).map(_.mkString).mkString(" ")
    res5: String = 0369 147 258
    

提交回复
热议问题