我正在编写一个解析器,其中将解析算术运算。此算术运算也包含变量,例如: VAR1 + 1
解析器如下:
package org.pvamu.hadoop.image;
import org.apache.spark.serializer.{KryoSerializer, KryoRegistrator}
import java.nio.file.Files;
import java.io.File;
import scala.util.parsing.combinator.lexical._
import scala.util.parsing.combinator.token.StdTokens
import scala.util.parsing.combinator.lexical.StdLexical
import scala.util.matching.Regex
import scala.util.parsing.combinator.syntactical._
import scala.util.parsing.combinator._
abstract class Expr {
def rpn:String
}
case class BinaryOperator(lhs:Expr, op:String, rhs:Expr) extends Expr {
def rpn:String = lhs.rpn + " " + rhs.rpn + " " + op
}
case class Number(v:String) extends Expr { def rpn:String = v }
case class Variable(v:String) extends Expr { def rpn:String = v }
case class Function(f:String, e:List[Expr]) extends Expr { def rpn:String = {
var s = ""
e.foreach { x => s += x.rpn + " " }
s += f
return s
}
}
class parseExp extends StandardTokenParsers {
lexical.delimiters ++= List("+","-","*","/","^","(",")",",")
def value :Parser[Expr] = numericLit ^^ { s => Number(s) }
def variable:Parser[Expr] = stringLit ^^ { s => Variable(s) }
def parens:Parser[Expr] = "(" ~> expr <~ ")"
def argument:Parser[Expr] = expr <~ (","?)
def func:Parser[Expr] = ( stringLit ~ "(" ~ (argument+) ~ ")" ^^ { case f ~ _ ~ e ~ _ => Function(f, e) })
def term = (value | parens | func | variable)
def pow :Parser[Expr] = ( term ~ "^" ~ pow ^^ {case left ~ _ ~ right => BinaryOperator(left, "^", right) }|
term)
def factor = pow * ("*" ^^^ { (left:Expr, right:Expr) => BinaryOperator(left, "*", right) } |
"/" ^^^ { (left:Expr, right:Expr) => BinaryOperator(left, "/", right) } )
def sum = factor * ("+" ^^^ { (left:Expr, right:Expr) => BinaryOperator(left, "+", right) } |
"-" ^^^ { (left:Expr, right:Expr) => BinaryOperator(left, "-", right) } )
def expr = ( sum | term )
def parse(s:String) = {
val tokens = new lexical.Scanner(s)
phrase(expr)(tokens)
}
def runParser(exprstr: String) : String = exprstr match {
case null => return ""
case "" => return ""
case _ =>
parse(exprstr) match {
case Success(tree, _) =>
println("Tree: "+tree)
val v = tree.rpn
println("RPN: "+v)
return v
case e: NoSuccess => Console.err.println(e)
return e.toString
}
}
}
object Calculator extends InfixToPostfix {
def main(args: Array[String]) {
println("input : "+ args(0))
println(runParser(args(0)))
}
}
然后作为输入我发送:“3 + j” 它给我一个错误说:
failure: string literal expected
3+j
^
我不知道哪个部分出了问题?! 我将解析一个路径和actual problem is here,但我意识到这个程序甚至无法解析一个小字符串,我不知道该如何处理它!