Last active
October 12, 2015 21:39
-
-
Save travisbrown/4091180 to your computer and use it in GitHub Desktop.
BufferedReader enumerator example for Scalaz 7 (with EitherT)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.{ BufferedReader, File, FileReader } | |
import scalaz._, Scalaz._, effect.IO, iteratee.{ Iteratee => I, _ } | |
object IterateeIOExample { | |
type ErrorOr[A] = EitherT[IO, Throwable, A] | |
def openFile(f: File) = IO(new BufferedReader(new FileReader(f))) | |
def readLine(r: BufferedReader) = IO(Option(r.readLine)) | |
def closeReader(r: BufferedReader) = IO(r.close()) | |
def tryIO[A, B](action: IO[B]) = I.iterateeT[A, ErrorOr, B]( | |
EitherT(action.catchLeft).map(I.sdone(_, I.emptyInput)) | |
) | |
def enumBuffered(r: => BufferedReader) = new EnumeratorT[String, ErrorOr] { | |
lazy val reader = r | |
def apply[A] = (s: StepT[String, ErrorOr, A]) => s.mapCont(k => | |
tryIO(readLine(reader)) flatMap { | |
case None => s.pointI | |
case Some(line) => k(I.elInput(line)) >>== apply[A] | |
} | |
) | |
} | |
def enumFile(f: File) = new EnumeratorT[String, ErrorOr] { | |
def apply[A] = (s: StepT[String, ErrorOr, A]) => | |
tryIO(openFile(f)).flatMap(reader => I.iterateeT[String, ErrorOr, A]( | |
EitherT( | |
enumBuffered(reader).apply(s).value.run.ensuring(closeReader(reader)) | |
) | |
)) | |
} | |
def main(args: Array[String]) { | |
val action = ( | |
I.consume[String, ErrorOr, List] %= | |
I.filter(_.count(_ == '0') >= 25) &= | |
enumFile(new File(args(0))) | |
).run.run | |
println(action.unsafePerformIO()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment