Skip to content

Instantly share code, notes, and snippets.

@stew
Created January 16, 2013 14:07
Show Gist options
  • Save stew/4547333 to your computer and use it in GitHub Desktop.
Save stew/4547333 to your computer and use it in GitHub Desktop.
example of kleisli in kleisli
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