Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created December 29, 2010 04:55
Show Gist options
  • Save debasishg/758194 to your computer and use it in GitHub Desktop.
Save debasishg/758194 to your computer and use it in GitHub Desktop.
Monadic & Non monadic
// 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