- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Scala Parser Combinators - SMALL Working Example
Sun, 2009-02-08, 18:16
I'm trying to get even a naive example of Scala's Parser Combinators to work
without success.
Looking at the PDF "Parser Combinators in Scala" the following example is
given:
import scala.util.parsing.combinator.syntactical.StdTokenParsers
import scala.util.parsing.combinator.lexical.StdLexical
object ArithmeticParser extends StdTokenParsers with Application {
type Tokens = StdLexical
val lexical = new StdLexical
lexical.delimiters ++= List("(", ")", "+", "-", "*", "/")
def factor: Parser[Int] = "(" ~ expr ~ ")" | numericLit ^^ (_.toInt)
def expr = term* ("+" ^^ { (x: Int, y: Int) => x + y } |
"-" ^^ { (x: Int, y: Int) => x - y })
def term = factor* ("*" ^^ { (x: Int, y: Int) => x * y } |
"/" ^^ { (x: Int, y: Int) => x / y })
Console.println (expr (new lexical.Scanner ("1+2*3*7-1") ))
}
However it fails to compile for me. Does anyone have a small similar
example of anykind, shape or form of using Scala's Parser Combinators which
works with the current 2.7.3 compiler?
Thank you.
import scala.util.parsing.combinator.syntactical.StdTokenParsers
import scala.util.parsing.combinator.lexical.StdLexical
object ArithmeticParser extends StdTokenParsers with Application {
type Tokens = StdLexical
val lexical = new StdLexical
lexical.delimiters ++= List("(", ")", "+", "-", "*", "/")
def factor: Parser[Int] = "(" ~> expr <~ ")" | numericLit ^^ (_.toInt)
def term : Parser[Int] = (
factor ~ "*" ~ term ^^ { case x ~ "*" ~ y => x * y } |
factor ~ "/" ~ term ^^ { case x ~ "/" ~ y => x / y } | factor )
def expr : Parser[Int] = (
term ~ "+" ~ expr ^^ { case x ~ "+" ~ y => x + y } |
term ~ "-" ~ expr ^^ { case x ~ "-" ~ y => x - y } | term )
Console.println (expr (new lexical.Scanner ("1+2*3*7-1") ))
}
On Sun, Feb 8, 2009 at 9:16 AM, Grey <ray [dot] racine [at] gmail [dot] com> wrote: