标签:编程 scala functional programmi
上期我们讨论了IO处理过程:Process[I,O]。我们说Process就像电视信号盒子一样有输入端和输出端两头。Process之间可以用一个Process的输出端与另一个Process的输入端连接起来形成一串具备多项数据处理功能的完整IO过程。但合成的IO过程两头输入端则需要接到一个数据源,而另外一端则可能会接到一个数据接收设备如文件、显示屏等。我们在这篇简单地先介绍一下IO数据源Source和IO数据接收端Sink。
我们先用一个独立的数据类型来代表数据源Source进行简单的示范说明,这个类型与Process类型没有任何关系:
import ProcessLib._ object SourceSink { trait Source[O] { //以下helper function都是把Source当作O类的List处理 def |>[O2](p: Process[O,O2]): Source[O2] //粘接一个Process p. 向其输入O def filter(f: O => Boolean): Source[O] = this |> Process.filter(f) //向p输入O def map[O2](f: O => O2): Source[O2] = this |> Process.lift(f) def take(n: Int): Source[O] = this |> Process.take(n) //截取前n个O def takeWhile(f: O => Boolean): Source[O] = this |> Process.takeWhile(f) def drop(n: Int): Source[O] = this |> Process.drop(n) //跳过前n个O def dropWhile(f: O => Boolean): Source[O] = this |> Process.dropWhile(f) }
我们再来看看一个Source特殊案例:
case class ResourceR[R,I,O]( //Source的一个只读资源案例 acquire: IO[R], //资源使用门户 resource handle release: R => IO[Unit], //完成使用资源后的清理函数 step: R => IO[Option[I]], //资源内容读取函数 trans: Process[I,O] //输出方式 ) extends Source[O] { def |>[O2](p: Process[O,O2]): Source[O2] = //实现抽象函数 ResourceR(acquire,release,step,trans |> p) //每次输入都产生一个ResourceR.它的trans与p进行管道对接 }
trait IO[A] { self => def run: A def map[B](f: A => B): IO[B] = new IO[B] { def run = f(self.run) } def flatMap[B](f: A => IO[B]): IO[B] = new IO[B] { def run = f(self.run).run } } object IO { def unit[A](a: => A): IO[A] = new IO[A] { def run = a } def flatMap[A,B](fa: IO[A])(f: A => IO[B]) = fa flatMap f def apply[A](a: => A): IO[A] = unit(a) // syntax for IO { .. } }
这个IO类型我们在前面的讨论里曾经练习过。
现在我们来看看一个文件读取的ResourceR例子:
object Source { import java.io._ def lines(fileName: String): Source[String] = //从文件fileName里读取String ResourceR( //创建一个Source的实例 IO {io.Source.fromFile(fileName) }, //资源 (src: io.Source) => IO { src.close }, //清理 (src: io.Source) => IO { //读取 lazy val iterator = src.getLines if (iterator.hasNext) Some(iterator.next) else None //读完返回None }, Process.passUnchanged) //Process[I,I],读什么输入什么 }
Source.lines("input.txt").count.exists{_ >= 40000 } //> res0: ch15.SourceSink.Source[Boolean] = ResourceR(ch15.SourceSink$IO$$anon$ //| 3@762efe5d,<function1>,<function1>,Await(<function1>))
def exists(f: O => Boolean): Source[Boolean] = this |> Process.exists(f) def count: Source[Int] = this |> Process.count
def collect: IO[IndexedSeq[O]] = { //读取数据源返回IO[IndexedSeq[O]], 用IO.run来实际运算 def tryOr[A](a: => A)(cleanup: IO[Unit]): A = //运算表达式a, 出现异常立即清理现场 try a catch {case e: Exception => cleanup.run; throw e} @annotation.tailrec //这是个尾递归算法,根据trans状态 def go(acc: IndexedSeq[O], cleanup: IO[Unit], step: IO[Option[I]], trans: Process[I,O]): IndexedSeq[O] = trans match { case Halt() => cleanup.run; acc //停止状态,清理现场 case Emit(out,next) => go(tryOr(out +: acc)(cleanup), cleanup, step, next) //积累acc case Await(iproc) => tryOr(step.run)(cleanup) match { case None => cleanup.run; acc //读完了清理现场 case si => go(acc,cleanup,step,iproc(si)) //读入元素作为Process输入来改变Process状态 } } acquire map {res => go(IndexedSeq(),release(res),step(res),trans)} //开始读取 }
与Source同样,我们还是用一个独立的类型Sink来代表数据接收端进行简单说明:
trait Sink[I] { def <|[I2](p: Process[I2,I]): Sink[I2] //p的输出接到Sink的输入 def filter(f: I => Boolean): Sink[I] = this <| Process.filter(f) //从p接收I def map[I2](f: I2 => I): Sink[I2] = this <| Process.lift(f) //将接收的I2变成I def take(n: Int): Sink[I] = this <| Process.take(n) //从p接收前n个I def takeWhile(f: I => Boolean): Sink[I] = this <| Process.takeWhile(f) def drop(n: Int): Sink[I] = this <| Process.drop(n) //过滤掉首n个I def dropWhile(f: I => Boolean): Sink[I] = this <| Process.dropWhile(f) }
同样,一个只写的资源实例如下:
case class ResourceW[R,I,I2]( //只写资源 acquire: IO[R], //资源使用门户, resource handle release: R => IO[Unit], //清理函数 rcvf: R => (I2 => IO[Unit]), //接收方式 trans: Process[I,I2] //处理过程 ) extends Sink[I] { def <|[I2](p: Process[I2,I]): Sink[I2] = ResourceW(acquire,release,rcvf,p |> trans) //制造一个ResourceW实例,由p到trans }
以下是一个向文件写入的Sink组件:
object Sink { import java.io._ def file(fileName: String, append: Boolean = false): Sink[String] = //结果是Sink[String]。必须用interpreter来运算 ResourceW( //是一个ResourceW实例 IO {new FileWriter(fileName,append) }, //创建FileWriter (w: FileWriter) => IO {w.close}, //释放FileWriter (w: FileWriter) => (s: String) => IO {w.write(s)}, //写入 Process.passUnchanged //不处理写入数据 ) }
版权声明:本文为博主原创文章,未经博主允许不得转载。
泛函编程(36)-泛函Stream IO:IO数据源-IO Source & Sink
标签:编程 scala functional programmi
原文地址:http://blog.csdn.net/tiger_xc/article/details/47271171