我正在使用Scala中的解释器,我需要找到一种方法来分配变量,名称和可以更新的值。示例输入可能如下所示
(x = x + 1) // results to: Assign("x",Plus(Var("x"),Num(1)))
非常感谢任何想法或建议。
答案 0 :(得分:1)
使用Scala的解析器组合器来解决这个问题,这是一个非常简单的起点。您可以使用此代码并将其展开以满足您的实际需求,但这应该向您展示基本概念:
trait Expression
case class Plus(a: Expression, b: Expression) extends Expression
case class Var(name: String) extends Expression
case class Num(n: Int) extends Expression
trait Statement
case class Assign(v: String, ex: Expression) extends Statement
object StatementParser extends RegexParsers {
private def num: Parser[Num] = regex(new Regex("""(\d+)""")).map(n => Num(n.toInt))
private def identifier: Parser[String] = regex(new Regex("""([A-Za-z][A-Za-z0-9]*)"""))
private def variable: Parser[Var] = identifier.map(Var(_))
private def expression: Parser[Expression] = plus | variable | num
private def plus: Parser[Plus] = ("(" ~> expression ~ "+" ~ expression <~ ")").map { case (l ~ _ ~ r) => Plus(l, r) }
private def assign: Parser[Assign] = (identifier ~ "=" ~ expression).map { case (v ~ _ ~ ex) => Assign(v, ex) }
private def parse(str: String): ParseResult[Statement] = parse(assign, str)
def apply(str: String): Statement = parse(str) match {
case Success(result: Statement, _) => result
case _ => sys.error("Could not parse the input string: " + str)
}
}
val s = StatementParser("x = (x + 1)")
println(s) // Assign(x,Plus(Var(x),Num(1)))