我试过
/* inside RegexParser class */
def exp : Parser[Exp] =
term~addop_chain ^^ {case l~ThenAdd(optype,r) => AritOp(l,optype,r)}
def addop_chain : Parser[Exp] =
("+"|"-")~term~addop_chain ^^ {case sym~term~ThenAdd(optype,r) => ThenAdd(sym, AritOp(term,optype,r)) } |
("+"|"-")~term ^^ {case sym~term => ThenAdd(sym, term)}
def term = /* right now, only int literal. code unrelevant */
/* Case classes for storing: */
case class ThenAdd(sym: String, r: Exp)
case class AritOp(l: Exp, sym: String, r: Exp)
哪个有效!,但是是右关联(不是左关联),例如5+(3-2),这不是我想要的。
我想要的是:
5+3-2
应该成为
AritOp(AritOp(5,+,3), -, 2)
(左关联)但是如果没有(正确?)左递归,这几乎是不可能的。我该怎么办?
(constriant:我不能使用rep, repsep, opt
(我正在做作业,所以语法应尽可能为BNF(即不是EBNF ))) p>