Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on Parsers Success In Scala

I'm new to Scala, and have been trying to use its excellent combinator parser library. I've been trying to get this code to compile:

import scala.util.parsing.combinator._
...
val r:Parsers#ParseResult[Node] = parser.parseAll(parser.suite,reader)
r match {
  case Success(r, n) => println(r)
  case Failure(msg, n) => println(msg)
  case Error(msg, n) => println(msg)
}
...

But I keep getting these errors:

TowelParser.scala:97: error: not found: value Success
  case Success(r, n) => println(r)
       ^
TowelParser.scala:98: error: not found: value Failure
  case Failure(msg, n) => println(msg)

TowelParser.scala:99: error: object Error is not a case class constructor, nor does it have an unapply/unapplySeq method
  case Error(msg, n) => println(msg)

I've tried lots of different things like:

case Parsers#Success(r, n) => println(r)

and

case Parsers.Success(r, n) => println(r)

and

import scala.util.parsing.combinator.Parsers.Success

But I can't seem to get this to compile. I'm sure there's probably something obvious I'm missing, but I've been at it for a while, and google doesn't seem to have any good examples of this.

Thanks!

like image 377
Alex Beal Avatar asked Dec 08 '12 17:12

Alex Beal


1 Answers

You need to specify the full path for the ParseResult, which includes your Parsers instance. For example:

import scala.util.parsing.combinator._

object parser extends RegexParsers { def digits = "\\d+".r ^^ (_.toInt) }

val res = parser.parseAll(parser.digits, "42")

res match {
  case parser.Success(r, n) => println(r)
  case parser.Failure(msg, n) => println(msg)
  case parser.Error(msg, n) => println(msg)
}

Note that you could also import these if you want a little extra syntactic convenience:

import parser.{ Error, Failure, Success }

Now your original version will work as expected.

like image 185
Travis Brown Avatar answered Oct 05 '22 20:10

Travis Brown