2 ms·
Scala's Parser-Combinators are about as good as you are going to get http://www.scala-blogs.org/2009/04/combinators-for-pretty-printers-part-1.html http://www.s
by lihaoyi 14y ago
Scala's Parser-Combinators are about as good as you are going to get http://www.scala-blogs.org/2009/04/combinators-for-pretty-printers-part-1.html http://www.scala-blogs.org/2009/04/combinators-for-pretty-pr.... Consider the grammar for simple math expressions:
expr ::= sum
sum ::= product { ("+" | "-") product }
product ::= power { ("*" | "/") power }
power ::= factor [ "^" factor ]
factor ::= "(" expr ")" | variable | constant
variable ::= identifier
constant ::= floatLiteral
It's pure-Scala is
def expr = sum
def sum = product ~ rep(("+" | "-") ~ product)
def product = power ~ rep(("*" | "/") ~ power)
def power = factor ~ opt("^" ~ factor)
def factor = "(" ~ expr ~ ")" | variable | constant
def variable = ident
def constant = floatLit
And since it's pure-Scala, you get all the benefit of static typing (error detection, auto-complete, etc) when writing your parser. There's also no extra compile step: your parser compiles with the rest of your program and is just a java Object with a parseAll() method.
Lastly, it's a superset of PEG, which means that its behavior and limitations are all pretty well-studied academically and well-defined (which is more than can be said of most hacked-together regex solutions!).
Pyparsing is pretty cool as well, for python, but it's somewhat more verbose since python isn't as DSL-friendly as scala: http://pyparsing.wikispaces.com/HowToUsePyparsing http://pyparsing.wikispaces.com/HowToUsePyparsing
EDIT: a (different) example from Pyparsing:
integer = Word( nums )
variable = Word( alphas, max=1 )
arithOp = Word( "+-*/", max=1 )
equation = variable + "=" + integer + arithOp + integer
As far as I can tell, Pyparsing is also a superset of PEG.