Pattern matching on Parsers Success In Scala

2019-06-20 05:17发布

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!

1条回答
走好不送
2楼-- · 2019-06-20 05:45

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.

查看更多
登录 后发表回答