Created
September 26, 2016 03:05
-
-
Save izmailoff/bfc1220cda5a8ce61eceeaa8efe72e13 to your computer and use it in GitHub Desktop.
Just an example of matching arbitrary length of list with a list of matchers (PF)
This file contains hidden or 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
val `namespace` = "namespace" | |
val `elementTerminator` = "elementTerminator" | |
val `openBracket` = "openBracket" | |
val `closeBracket` = "closeBracket" | |
// list of partial functions from list of strings to string: | |
val patterns = List[PartialFunction[List[String], String]]( | |
{ case `namespace` :: value :: `elementTerminator` :: rest => "case1" }, | |
{ case `openBracket` :: rest => "case2" }, | |
{ case `closeBracket` :: `elementTerminator` :: rest => "case3" }) | |
def matchingAndDispatch(xs: List[String], patterns: List[PartialFunction[List[String], String]]): String = | |
patterns.find(_.isDefinedAt(xs)).map(_(xs)).getOrElse("unknown") | |
// Test/Outputs: | |
matchingAndDispatch(List("namespace", "somevalue", "elementTerminator"), patterns) | |
// case1 | |
matchingAndDispatch(List("namespace", "somevalue", "elementTerminator", "more"), patterns) | |
// case1 | |
matchingAndDispatch(List("namespace", "somevalue", "not_terminator", "more"), patterns) | |
// unknown |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment