Skip to content

Instantly share code, notes, and snippets.

@cvogt
Last active February 26, 2016 18:09
Show Gist options
  • Save cvogt/6d68975e581dad5af09a to your computer and use it in GitHub Desktop.
Save cvogt/6d68975e581dad5af09a to your computer and use it in GitHub Desktop.
Monadic Context Nirvana
case class Person(name: String, livesAt: Int, isRich: Boolean )
case class Address(city: String)
// main
println( showPerson(1) )
println( showPerson(2) )
// Blocking
object DAO{
// Sample data coming from Database
def personById(id: Int): Person = ???
def addressById(id: Int): Address = ???
}
// non monadic
def showPerson(id: Int) = {
val p = DAO.personById(id)
p.name ++ ( if(p.isRich) " is rich and lives in " ++ DAO.addressById( p.livesAt ).text else "" )
}
// Non-blocking
object DAO{
// Sample data coming from Database
def personById(id: Int): Future[Person] = ...
def addressById(id: Int): Future[Address] = ...
}
// monadic using for
def showPerson(id: Int) = for{
p <- DAO.personById(id)
res <- if(p.isRich) DAO.addressById( p.livesAt ).map( a => " is rich and lives in " ++ a.text) else Future.successful("")
} yield p.name ++ res
// monadic using flow comprehensions
def showPerson(id: Int) = Future.flat{ implicit context =>
val p = DAO.personById(id)
p.name ++ ( if(p.isRich) " is rich and lives in " ++ DAO.addressById( p.livesAt ).text else "" )
}
// (DAO dummy impl to run this)
object DAO{
// Sample data coming from Database
def personById(id: Int): Person = {
Map(
1 -> Person("Peter", 1, false),
2 -> Person("Kevin", 2, true)
)(id)
}
def addressById(id: Int): Address = {
Map(
1 -> Address("Brooklyn"),
2 -> Address("Upper East Side")
)(id)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment