Created
January 16, 2013 14:07
-
-
Save stew/4547333 to your computer and use it in GitHub Desktop.
example of kleisli in kleisli
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._ | |
import Scalaz._ | |
case class Person(name: String, score: Int) | |
object Main extends App { | |
type Environment = Map[String, Person] | |
type EnvReader[+A] = Kleisli[Option,Environment,A] | |
type UserReader[+A] = Kleisli[EnvReader,String,A] | |
implicit def toEnvReader[A](f: Environment => Option[A]) : EnvReader[A] = Kleisli(f) | |
implicit def toUserReader[A](f: String => EnvReader[A]) : UserReader[A] = Kleisli(f) | |
def getPerson0(username : String): EnvReader[Person] = { env : Environment => | |
env.get(username) | |
} | |
val getPerson: UserReader[Person] = getPerson0 _ | |
def getName: UserReader[String] = getPerson map ((p: Person) => p.name) | |
def getScore : UserReader[Int] = getPerson map ((p: Person) => p.score) | |
def bio : UserReader[String] = | |
for { | |
name <- getName | |
score <- getScore | |
} yield(name + " got score: " + score) | |
val environment : Environment = Map("stew" -> Person("Mike O'Connor", 12)) | |
// Mike O'Connor got score: 12 | |
println(bio("stew")(environment) getOrElse "not found") | |
// not found | |
println(bio("john")(environment) getOrElse "not found") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment