문제

I have elements from an Enumerator[A], and want to group/batch the elements to get an Enumerator[Seq[A]]. Here's code I wrote which groups A to Seq[A], but doesn't produce an Enumerator[Seq[A]].

val batchSize = 1000
dogsEnumerator
  .run(
    Iteratee.fold1[Dog, Vector[Dog]](Future.successful(Vector[Dog]())){
      (r, c) =>
        if (r.size > batchSize)
          processBatch(r).map(_ => Vector[Dog]())
        else
          Future.successful(r :+ c)
    }.map(_ => ())
  )
도움이 되었습니까?

해결책

This can be done pretty straightforwardly with the help of some of the Enumeratee combinators:

import play.api.libs.iteratee._

def batch[A](n: Int): Enumeratee[A, List[A]] = Enumeratee.grouped(
  Enumeratee.take(n) &>> Iteratee.getChunks[A]
)

We can then use this enumeratee to transform any enumerator into a new enumerator of lists:

val intsEnumerator = Enumerator(1 to 40: _*)

intsEnumerator.through(batch(7)).run(Iteratee.foreach(println))

This will print the following:

List(1, 2, 3, 4, 5, 6, 7)
List(8, 9, 10, 11, 12, 13, 14)
List(15, 16, 17, 18, 19, 20, 21)
List(22, 23, 24, 25, 26, 27, 28)
List(29, 30, 31, 32, 33, 34, 35)
List(36, 37, 38, 39, 40)

As expected.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top