This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!

why monads

By: vincentmarquez on Apr 19th, 2013  |  syntax: Scala  |  size: 1.51 KB  |  views: 126  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. //why monads tutorial
  2.  
  3. class CompanyInfo { /* important shit here */ }
  4.  
  5. def getCompanyInfoFromDB(user: User, companyname: String) = ??? //prototype method
  6.  
  7. //java style classes
  8. class Company { var name: String }
  9. class User { var company: Company }
  10. class Session { var user: User }
  11.  
  12. def getCompanyInfo(session: Session, newname: String): CompanyInfo {
  13.    //BIG FAT RACE CONDITION, POSSIBLE NPE. NOT THREAD SAFE
  14.    if (session.user != null && session.user.company != null)
  15.      return getCompanyInfoFromDB(session.user, session.user.company.name)
  16.    else
  17.     return null
  18. }
  19.  
  20. //Functional (mutable) style
  21. class Company { var name: Option[String] }
  22. class User { var company: Option[Company] }
  23. class Session { var user: Option[User] }
  24.  
  25. def getCompanyInfoDesugared(session: Session, newname: String): Option[CompanyInfo] {
  26.    //what is really happening:
  27.    return session.user.flatMap(user =>
  28.         user.company.flatMap(company =>
  29.                 company.name.map(compname =>
  30.                         getCompanyInfoFromDB(user, compname)
  31.                 )
  32.        )
  33.    )
  34. }
  35. //Equivalent to above code, just using scala's monad syntax
  36. def getCompanyInfoMonadic(session: Session, newname: String): Option[CompanyInfo] {
  37.    //MONADIC STYLE BECAUSE OPTION IS A MONAD!!!
  38.    return for {
  39.         user <- session.user
  40.       company<- user.company //if any of these are None, we terminate and return None
  41.          name<- company.name
  42.         //we could keep going deeper, doesn't matter no nesting syntax!
  43.     } yield
  44.         getCompanyInfoFromDB(user, name)
  45. }
clone this paste RAW Paste Data