Play Framework Enumerator:如何使用Index压缩枚举器

时间:2015-07-30 19:22:28

标签: scala playframework enumerator

假设我有一个枚举器

val e:Enumerator [String] = Enumerator(" a"," b"," c")

和另一个自然数的调查员

val count = Enumerator.enumerate(Iterator.from(1))

我怎样才能生成一个拉链它们的枚举器。或者用索引拉链e。 所以在这种情况下输出是: val zipped:Enumerator [(String,Int)] = Enumerator((" a",1),(" b",2),(" c", 3))

1 个答案:

答案 0 :(得分:1)

I'm somewhat new to Iteratees but since there are no responses yet, I will share my less than expert knowledge.

It seems like there should be a zip operator that does what you describe. The closest is interleave, but based on my understanding of its behavior, I don't think it will fit you use case.

If you just need an index for each element you could use something like this (I acknowledge the ugly mutable state)

scala> import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.ExecutionContext.Implicits.global

scala> import play.api.libs.iteratee._
import play.api.libs.iteratee._

scala> var counter = -1
counter: Int = -1

scala> Enumerator("a", "b", "c").map[(String, Int)]{ s => counter+=1; (s, counter) }
res1: play.api.libs.iteratee.Enumerator[(String, Int)] = play.api.libs.iteratee.Enumerator$$anon$3@3c0c6967

scala> res1 run Iteratee.foreach( println _ )
(a,0)
(b,1)
res2: scala.concurrent.Future[Unit] = scala.concurrent.impl.Promise$DefaultPromise@7814bb7d
(c,2)

scala>

If you want something that doesn't close around a var (as you should!) you could look into implementing this functionality on the side of the iteratee and pass the counter around as state in the Step process.