How to get left assoc operators with scala combinators?

自古美人都是妖i 提交于 2019-12-24 17:46:25

问题


I've tried

/* 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)

Which works!, but is right-assoc (not left-assoc), e.g. 5+(3-2), which is not what I want.

What I want is something like:

5+3-2

should become

AritOp(AritOp(5,+,3), -, 2)

(left assoc) But this feels almost impossible without (proper?) left recursion. What can I do?

(constriant: I can't use rep, repsep, opt (I'm doing an assignment, so the grammer should be as BNF as possible (ie. not EBNF)))

来源:https://stackoverflow.com/questions/15729412/how-to-get-left-assoc-operators-with-scala-combinators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!