Created
July 1, 2012 11:44
-
-
Save stew/3028132 to your computer and use it in GitHub Desktop.
Reader Monad + Validation
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._ | |
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