这个问题促使我们尝试使用组合解析器。给定以下代表表达式子集的代数数据类型:
import scala.util.parsing.combinator._
object Expr { type VARS = Map[String, Any] }
import Expr._
sealed trait Expr { def eval(v: VARS) : Any }
case class If(cond: Cond, ifTrue: Expr, ifFalse: Expr) extends Expr {
def eval(v: VARS) =
if (cond.eval(v)) ifTrue.eval(v) else ifFalse.eval(v)
}
case class Cond(left: Expr, right: Expr) extends Expr {
def eval(v: VARS) = left.eval(v) == right.eval(v)
}
case class Len(ident: String) extends Expr {
def eval(v: VARS) = v(ident).toString.size
}
case class Mid(ident: String, start: Expr, count: Expr) extends Expr {
def eval(v: VARS) = {
val s = start.eval(v).asInstanceOf[Int]
val e = s + count.eval(v).asInstanceOf[Int]
v(ident).asInstanceOf[String].substring(s, e)
}
}
case class Ident(ident: String) extends Expr { def eval(v:VARS) = v(ident) }
case class StringLit(value: String) extends Expr { def eval(v:VARS) = value }
case class Number(value: String) extends Expr { def eval(v:VARS) = value.toInt }
以下解析器定义将解析您的给定表达式并返回一个Expr
对象:
class Equation extends JavaTokenParsers {
def IF: Parser[If] = "IF" ~ "(" ~ booleanExpr ~","~ expr ~","~ expr ~ ")" ^^ {
case "IF" ~ "(" ~ booleanExpr ~ "," ~ ifTrue ~ "," ~ ifFalse ~ ")" =>
If(booleanExpr, ifTrue, ifFalse)
}
def LEN: Parser[Len] = "LEN" ~> "(" ~> ident <~ ")" ^^ (Len(_))
def MID: Parser[Mid] = "MID" ~ "(" ~ ident ~ "," ~ expr ~ "," ~ expr ~ ")" ^^ {
case "MID" ~ "(" ~ ident ~ "," ~ expr1 ~ "," ~ expr2 ~ ")" =>
Mid(ident, expr1, expr2)
}
def expr: Parser[Expr] = (
stringLiteral ^^ (StringLit(_))
| wholeNumber ^^ (Number(_))
| LEN
| MID
| IF
| ident ^^ (Ident(_))
)
def booleanExpr: Parser[Cond] = expr ~ "=" ~ expr ^^ {
case expr1 ~ "=" ~ expr2 => Cond(expr1, expr2)
}
}
然后解析和评估结果可以这样完成:
val equation = new Equation
val parsed = equation.parseAll(equation.expr,
"""IF(LEN(param1)=4,MID(param1,2,1), MID(param1,0,LEN(param1)))""")
parsed match {
case equation.Success(expr, _) =>
println(expr)
// If(Cond(Len(param1),Number(4)),
// Mid(param1,Number(2),Number(1)),
// Mid(param1,Number(0),Len(param1)))
println(expr.eval(Map("param1" -> "scala"))) // prints scala
println(expr.eval(Map("param1" -> "scat"))) // prints a
case _ =>
println("cannot parse")
}
请注意,我提供的语法只是使您的示例解析的最低要求,并且绝对没有错误管理或类型检查。过程明智,我首先想出了一个语法,没有^^ ...
可以解析您的示例的产生式,然后添加了Expr
类型但没有 eval 方法,然后是 production ^^ ...
,最后我将 eval 方法添加到Expr
特征和子类中。