Skip to content

Instantly share code, notes, and snippets.

@ahanwadi
Created February 25, 2017 21:50
Show Gist options
  • Select an option

  • Save ahanwadi/29a99c3d63c686a79c58133e84d4967a to your computer and use it in GitHub Desktop.

Select an option

Save ahanwadi/29a99c3d63c686a79c58133e84d4967a to your computer and use it in GitHub Desktop.
Free Monad in scalar
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)
}
@ahanwadi
Copy link
Author

Loading...
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 $ivy.$ , scalaz., Scalaz., scalaz.Free._
@ import $file.FreeMonadTest, FreeMonadTest.FreeMonadTest._
Compiling FreeMonadTest.sc
import $file.$ , FreeMonadTest.FreeMonadTest._
@ prog.foldMap(Konsole)
What's your name
Ashish
how are you, Ashish

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment