Scalaz iteratee,为BufferedReader创建Enumerator

时间:2012-02-22 14:53:56

标签: scala scalaz

如何为BufferedReader创建Enumerator?

我找到了相当旧的文章:http://apocalisp.wordpress.com/2010/10/17/scalaz-tutorial-enumeration-based-io-with-iteratees/,看起来它与Scalaz 6.0.4不兼容

我尝试根据示例创建Enumerator: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))))
   }
 }

但我无法理解如何将IO monad与Enumerator结合起来

1 个答案:

答案 0 :(得分:3)

Rúnar的文章有什么问题?以下版本适用于我(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))
}