11
我有以下EBNF,我想分析:EBNF Scala的解析器組合
PostfixExp -> PrimaryExp ("[" Exp "]"
| . id "(" ExpList ")"
| . length)*
這是我得到:
def postfixExp: Parser[Expression] = (
primaryExp ~ rep(
"[" ~ expression ~ "]"
| "." ~ ident ~"(" ~ repsep(expression, ",") ~ ")"
| "." ~ "length") ^^ {
case primary ~ list => list.foldLeft(primary)((prim,post) =>
post match {
case "[" ~ length ~ "]" => ElementExpression(prim, length.asInstanceOf[Expression])
case "." ~ function ~"(" ~ arguments ~ ")" => CallMethodExpression(prim, function.asInstanceOf[String], arguments.asInstanceOf[List[Expression]])
case _ => LengthExpression(prim)
}
)
})
但我想知道是否有一個更好的方法,最好不必訴諸鑄造(asInstanceOf)。