Created
February 15, 2012 19:24
-
-
Save devth/1838316 to your computer and use it in GitHub Desktop.
A comparison of pattern matching and equivalent imperative solution
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
// 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