Created
December 29, 2010 04:55
-
-
Save debasishg/758194 to your computer and use it in GitHub Desktop.
Monadic & Non monadic
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
// sample snippet that does not use monads | |
// note explicit null checks and imperative flow | |
String param(String key) { | |
//.. fetch value from request/session | |
return value; | |
} | |
Trade queryTrade(String ref) { | |
//.. query from db | |
return trade | |
} | |
public static void main(String[] args) { | |
String key; | |
//.. set key | |
String refNo = param(key); | |
if (refNo == null) { | |
//.. exception processing | |
} | |
Trade trade = queryTrade (refNo); | |
if (trade == null) { //.. explicit null check | |
//.. exception processing | |
} | |
} | |
// monadic version | |
def param(key: String): Option[String] = { //.. monadic return | |
//.. | |
} | |
def queryTrade(ref: String): Option[Trade] = { //.. monadic return | |
//.. | |
} | |
def main(args: Array[String]) { | |
// monadic comprehension block | |
// automatic sequencing plus NO explicit null handling | |
// makes program structure look better | |
val trade = | |
( | |
for { | |
r <- param("refNo") | |
t <- queryTrade (r) | |
} | |
yield t | |
) getOrElse error("not found") | |
//.. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment