Skip to content

Instantly share code, notes, and snippets.

@devth
Created February 15, 2012 19:24
Show Gist options
  • Save devth/1838316 to your computer and use it in GitHub Desktop.
Save devth/1838316 to your computer and use it in GitHub Desktop.
A comparison of pattern matching and equivalent imperative solution
// groups only holds lists of "good" things and "bad" things
val groups = Map('good -> List("beer", "bikes"), 'bad -> List("flat tires"))
// But we're interested in both "good" things and "not too bad" things
val known = (groups.get('good), groups.get('notTooBad)) match {
case (Some(goodThings), Some(notTooBadThings)) => "i know about good and not-too-bad things"
case (Some(goodThings), None) => "i know about good things only"
case (_, None) => "i might know about good things but nothing else"
case _ => "i may or may not know anything"
}
// Here's an imperative equivalent
var goodThings = null
var notTooBadThings = null
if (groups.containsKey('good))
goodThings = groups('good)
if (groups.containsKey('notTooBad))
notTooBadThings = groups('notTooBad)
val knownImperative =
if (goodThings != null && notTooBadThings != null) "i know about good and not-too-bad things"
else if (goodThings != null && notTooBadThings == null) "i know about good things only"
else if (notTooBadThings == null) "i might know about good things but nothing else"
else "i may or may not know anything"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment