Skip to content

Instantly share code, notes, and snippets.

@stew
Created July 1, 2012 11:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stew/3028132 to your computer and use it in GitHub Desktop.
Save stew/3028132 to your computer and use it in GitHub Desktop.
Reader Monad + Validation
import scalaz._
import Scalaz._
object Foo {
type Result[A] = Validation[String,A]
type Reader[A] = Int => Result[A]
implicit val readerBind: Bind[Reader] = new Bind[Reader] {
def map[A,B](fa: Reader[A])(f: A=>B) : Reader[B] = x => fa(x) map f
def bind[A,B](fa: Reader[A])(f: A => Reader[B]) : Reader[B] = {
x =>
fa(x) match {
case Success(a) => f(a)(x)
case Failure(f) => Failure(f)
}
}
}
implicit def resultMonad = Validation.validationMonad
def add(x: Int): Reader[Int] = y => (x+y+3).success
def str(x: Int): Reader[String] = y => (x*y).toString.success
def composeThem(a: Int) : Reader[String] = add(a).flatMap(str)
def main(args: Array[String]) = {
println(composeThem(1)(2)) // should be (1 + 2 + 3) * 2 as a string
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment