Last active
January 2, 2016 12:59
-
-
Save ble/8306667 to your computer and use it in GitHub Desktop.
Simple parser combinator example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.parsing.combinator._ | |
import scala.util.parsing.input.CharSequenceReader | |
object Simple { | |
trait Expression | |
case class Add(lhs: Expression, rhs: Expression) extends Expression | |
case class Mul(lhs: Expression, rhs: Expression) extends Expression | |
case class Num(v: Double) extends Expression | |
object parseUtil extends JavaTokenParsers | |
import parseUtil._ | |
def expr = term | |
def term = factor.*("+" ^^^ ((l: Expression, r: Expression) => Add(l,r))) | |
def factor = primary.*("*" ^^^ ((l: Expression, r: Expression) => Mul(l,r))) | |
def primary: Parser[Expression] = floatingPointNumber ^^ (x => Num(x.toDouble)) | |
} | |
val expression = Simple.expr(new CharSequenceReader("3 * 6 + 1 * 2")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment