-
-
Save petekneller/0fc051504a67ffef7b43 to your computer and use it in GitHub Desktop.
This file contains 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.effect.IO | |
import scalaz.{EitherT, Monad} | |
object Program extends ProgramInstances { | |
def apply[A](a: A): Program[A] = Program[A](EitherT.right[IO, Throwable, A](IO(a))) | |
} | |
trait ProgramInstances { | |
implicit object ProgramMonad extends Monad[Program] { | |
override def point[A](a: => A): Program[A] = Program[A](a) | |
override def bind[A, B](fa: Program[A])(f: A => Program[B]): Program[B] = fa flatMap f | |
} | |
} | |
case class Program[A](program: EitherT[IO, Throwable, A]) { | |
def map[B](f: A => B): Program[B] = | |
Program(program.map(a => f(a))) | |
def flatMap[B](f: A => Program[B]): Program[B] = | |
Program(program.flatMap(a => f(a).program)) | |
} | |
object Main { | |
def getXml(): Program[String] = Program("<bananas count='3'>") | |
def howManyBananas(xml: String): Program[Int] = Program(3) | |
val countBananas: Program[Int] = for { | |
xml <- getXml() | |
bananaCount <- howManyBananas(xml) | |
} yield bananaCount | |
val anyBananas: Program[String] = for { | |
bananaCount <- countBananas | |
} yield if (bananaCount == 0) "Yes, we have no bananas" else "No, we don't have no bananas" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment