Pattern matching on Parsers Success In Scala

拈花ヽ惹草 提交于 2019-12-10 13:43:01

问题


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:


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.



来源:https://stackoverflow.com/questions/13780139/pattern-matching-on-parsers-success-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!