gpt4 book ai didi

Scalaz iteratee,为 BufferedReader 创建 Enumerator

转载 作者:行者123 更新时间:2023-12-02 00:24:32 26 4
gpt4 key购买 nike

如何为 BufferedReader 创建枚举器?

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

我尝试根据此处的示例创建枚举器: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 结合使用

最佳答案

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))
}

关于Scalaz iteratee,为 BufferedReader 创建 Enumerator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9397131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com