Created
February 25, 2017 21:50
-
-
Save ahanwadi/29a99c3d63c686a79c58133e84d4967a to your computer and use it in GitHub Desktop.
Free Monad in scalar
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._, Scalaz._, scalaz.Free._ | |
| object FreeMonadTest { | |
| sealed trait Interact[A] | |
| case class Ask(prompt: String) extends Interact[String] | |
| case class Tell(msg: String) extends Interact[Unit] | |
| type Dsl[A] = Free[Interact, A] | |
| def ask(prompt: String): Dsl[String] = Free.liftF(Ask(prompt)) | |
| def tell(what: String): Dsl[Unit] = Free.liftF(Tell(what)) | |
| def prog = for { | |
| x <- ask("What's your name") | |
| _ <- tell(s"how are you, $x") | |
| } yield () | |
| implicit object Konsole extends (Interact ~> Id) { | |
| def apply[A](i: Interact[A]) = i match { | |
| case Ask(prompt) => println(prompt); scala.io.StdIn.readLine | |
| case Tell(what) => println(what) | |
| } | |
| } | |
| // Execute the prog as: prog.foldMap(Konsole) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Loading...$ivy.$ , scalaz., Scalaz., scalaz.Free._$file.$ , FreeMonadTest.FreeMonadTest._
Welcome to the Ammonite Repl 0.8.2
(Scala 2.12.1 Java 1.8.0_112)
@ import $ivy.
org.scalaz::scalaz-core:7.2.7, scalaz., Scalaz., scalaz.Free._import
@ import $file.FreeMonadTest, FreeMonadTest.FreeMonadTest._
Compiling FreeMonadTest.sc
import
@ prog.foldMap(Konsole)
What's your name
Ashish
how are you, Ashish