How is it possible to create Enumerator for BufferedReader?
I found rather old article: http://apocalisp.wordpress.com/2010/10/17/scalaz-tutorial-enumeration-based-io-with-iteratees/ and it looks like it doesn't work with Scalaz 6.0.4
I try to create Enumerator based on example from here: Idiomatic construction to check whether a collection is ordered
implicit val ListEnumerator = new Enumerator[List] {
def apply[E, A](e: List[E], i: IterV[E, A]): IterV[E, A] = e match {
case List() => i
case x :: xs => i.fold(done = (_, _) => i,
cont = k => apply(xs, k(El(x))))
}
}
But I can't understand how to combine IO monad with Enumerator
What's wrong with Rúnar's article? The following version is working for me (Scalaz 6.0.4):
object FileIteratee {
def enumReader[A](r: BufferedReader, it: IterV[String, A]) : IO[IterV[String, A]] = {
def loop: IterV[String, A] => IO[IterV[String, A]] = {
case i@Done(_, _) => i.pure[IO]
case i@Cont(k) => for {
s <- r.readLine.pure[IO]
a <- if (s == null) i.pure[IO] else loop(k(El(s)))
} yield a
}
loop(it)
}
def bufferFile(f: File) = new BufferedReader(new FileReader(f)).pure[IO]
def closeReader(r: Reader) = r.close().pure[IO]
def bracket[A,B,C](init: IO[A], fin: A => IO[B], body: A => IO[C]): IO[C] =
for {
a <- init
c <- body(a)
_ <- fin(a)
} yield c
def enumFile[A](f: File, i: IterV[String, A]) : IO[IterV[String, A]] =
bracket(bufferFile(f),
closeReader(_: BufferedReader),
enumReader(_: BufferedReader, i))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With