流式处理与增量 I/O 深入解析
1. 简单流转换与文件处理
在流处理中,我们可以轻松地表达行计数问题的核心转换,例如使用 count andThen exists(_ > 40000) 。而且,为管道添加过滤器和其他转换也十分便捷。
当处理文件时,我们最初的问题是判断文件是否包含超过 40,000 个元素。现在,我们可以将文件作为流的元素来源,并且将流的所有输出组合成一个最终值。以下是相关的代码实现:
def fromIterator[O](itr: Iterator[O]): Stream[O] =
Pull.unfold(itr)(itr =>
if itr.hasNext then Right((itr.next(), itr))
else Left(itr)
).void.toStream
def processFile[A](
file: java.io.File,
p: Pipe[String, A],
)(using m: Monoid[A]): IO[A] = IO:
val source = scala.io.Source.fromFile(file)
try fromIterator(source.getLines).pipe(p).fold(m.empty)(m.combine)
finally source.close()
def checkFileForGt40K(file: java.io.File): IO[Boolean] =
processFile(file, count andThen ex
超级会员免费看
订阅专栏 解锁全文
940

被折叠的 条评论
为什么被折叠?



