使用Scala,有没有办法动态构建列表模式以进行模式匹配?
例如,假设我使用稳定标识符来解析字符串列表,如下所示:
def matchingAndDispatch(xs: List[String])= {
case `namespace` :: value :: `elementTerminator` :: rest => {
// Do Something...
}
case `openBracket` :: rest => {
// Do Something Else...
}
case `closeBracket` :: `elementTerminator` :: rest => {
// Or perhaps something else...
}
}
现在,假设会有很多case子句,我希望能够将它们存储在某种可以在运行时更改的集合中 - 不一定是模式本身,但模式的集合可能是改变。我在下面的代码中编写了想象类MatchClause,以便或多或少地解释我的想法 - 基本上遍历模式集合(即匹配子句)并一次匹配一个:
def matchingAndDispatch(xs: List[String], matchingClauses:List[MatchClause])= {
if(!matchingClauses.empty){
case matchingClauses.head => {
// Do Something...
}
case _ => matchingAndDispatch(xs, matchingClause.tail)
}
}else throw new Error("no match")
Scala API中是否有任何可用于此目的的内容?我还没找到任何东西。或者我可能以错误的方式解决这个问题?
答案 0 :(得分:3)
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")
}
测试:
matchingAndDispatch(List("namespace", "somevalue", "elementTerminator"), patterns)
> case1
matchingAndDispatch(List("namespace", "somevalue", "elementTerminator", "more"), patterns)
> case1
matchingAndDispatch(List("namespace", "somevalue", "not_terminator", "more"), patterns)
> unknown
答案 1 :(得分:0)
您可以在本地范围内声明稳定标识符。也就是说,你可以写
val hd = matchingClauses.head
xs match {
case `hd` => ???
}