This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Scala Parser Combinators - SMALL Working Example

1 reply
Grey
Joined: 2009-01-03,
User offline. Last seen 42 years 45 weeks ago.

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.

Christian Szegedy
Joined: 2009-02-08,
User offline. Last seen 42 years 45 weeks ago.
Re: Scala Parser Combinators - SMALL Working Example

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:

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:


Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland