split a stream in many

后端 未结 6 1639
清酒与你
清酒与你 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:40

    The only thing I can think of:

    def distribute[T](n: Int)(x: Stream[T]) = (0 until n).map { p =>
      x.zipWithIndex.collect {
        case (e,i) if i % n == p => e
      }
    }
    

    It's kind of ugly because each of the sub-streams has to entirely traverse the main-stream. But I don't think you can mitigate that while preserving (apparent) immutability.

    Have you thought of dispatching individual tasks to actors and having a "task-distributer" that does exactly this?

提交回复
热议问题