Created
September 8, 2015 13:55
-
-
Save ssmylh/c38fffeec2c4cab58704 to your computer and use it in GitHub Desktop.
Implement Console of FP in Scala using Scalaz v7.2.0-M3
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 scalaz._ | |
| import scalaz.Free._ | |
| import scalaz.std.function._ | |
| import scalaz.{ Free, ~> } | |
| sealed trait Console[A] | |
| case object ReadLine extends Console[Option[String]] | |
| case class PrintLine(line: String) extends Console[Unit] | |
| object Console { | |
| type ConsoleIO[A] = Free[Console, A] | |
| def readLn: ConsoleIO[Option[String]] = liftF(ReadLine) | |
| def printLn(line: String): ConsoleIO[Unit] = liftF(PrintLine(line)) | |
| } | |
| object ConsoleApp extends App { | |
| import Console._ | |
| val console2Function0 = new (Console ~> Function0) { | |
| override def apply[A](fa: Console[A]): () => A = fa match { | |
| case ReadLine => () => Some(io.StdIn.readLine()) | |
| case PrintLine(line) => () => println(line) | |
| } | |
| } | |
| val msg = "I can only interact with the console." | |
| val f = for { | |
| _ <- printLn(msg) | |
| line <- readLn | |
| } yield line | |
| val r1: Free[Function0,Option[String]] = f.mapSuspension(console2Function0) | |
| println(r1.run) | |
| val r2: () => Option[String] = f.foldMap(console2Function0) | |
| println(r2()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment