Created
November 25, 2014 16:37
-
-
Save stacycurl/f7660f0f3aac04e2254a to your computer and use it in GitHub Desktop.
Program[Bananas]
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.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