Scala 㧠Iteratee 㨠Enumerator ãæ¸ãç·´ç¿
ã¨ãããã使ãæ¹ã ãã¡ã¢
package com.github.cooldaemon.scalaz_test import scalaz._ object TryIteratee { import Scalaz._ import IterV._ def run { implicit val ListEnum = new Enumerator[Seq] { def apply[E, A](e: Seq[E], i: IterV[E, A]): IterV[E, A] = { e match { case Seq() => i case x::xs => i.fold( done = (_, _) => i, cont = k => apply(xs, k(El(x))) ) } } } implicit val StreamEnum = new Enumerator[Stream] { def apply[E, A](e: Stream[E], i: IterV[E, A]): IterV[E, A] = { e match { case Stream() => i case x #:: xs => i.fold( done = (_, _) => i, cont = k => apply(xs, k(El(x))) ) } } } val seq = Seq.range(1, 5) head(seq).run assert_=== Some(1) val m = for { x <- head[Int] y <- head[Int] } yield (x, y) m(seq).run assert_=== (Some(1), Some(2)) def dropAndPrintAll[E] :IterV[E, Unit] = { def step(s: Input[E]) :IterV[E, Unit] = { s( el = {e => println(e) Cont(step) }, empty = Cont(step), eof = Done((), EOF[E]) ) } Cont(step) } println("--<èªä½ Iteratee>--") dropAndPrintAll(seq).run def peekAndPrintAll[E] :IterV[E, Unit] = { def step(initS: Input[E])(s: Input[E]): IterV[E, Unit] = { s( el = {e => println(e) Cont(step(initS)) }, empty = Cont(step(initS)), eof = Done((), initS) ) } Cont({s => step(s)(s)}) } val m2 = for { _ <- peekAndPrintAll[Int] x <- head[Int] } yield x println("--<Iteratee ã®åæ>--") m2(seq).run assert_=== Some(1) println("--<Enumerator ãå¾ãã追å >--") val m3 = dropAndPrintAll(seq) val m4 = m3(Stream.range(5, 10)) // Seq ã« Stream ã追å ãã¦ãè¯ã m4.run } }
解説ã¯å¾ã§ãä¾ã¨ã¯è¨ã Iteratee ã®ä¸ã«å¯ä½ç¨ãåå¨ããæãããµãã
çåç¹ãã®1
ä¸è¨ãæ«å°¾å帰ã«ããã«ã¯â¦
def apply[E, A](e: Seq[E], i: IterV[E, A]): IterV[E, A] = { e match { case Seq() => i case x::xs => i.fold( done = (_, _) => i, cont = k => apply(xs, k(El(x))) ) } }
ä¸è¨ã®ããã«ããå¿ è¦ããããä½ã§ã ãã¼ï¼
@annotation.tailrec def apply[E, A](e: Seq[E], i: IterV[E, A]): IterV[E, A] = { val next: Option[(Seq[E], IterV[E, A])] = e match { case Seq() => None case x::xs => i.fold( done = (_, _) => None, cont = k => some((xs, k(El(x)))) ) } next match { case None => i case Some((es, is)) => apply(es, is) } }
çåç¹ãã®2
Haskell ã¿ããã« Enumerator å士ãåæããæ¹æ³ã解ããªã