Scala中解析器成功的模式匹配 [英] Pattern matching on Parsers Success In Scala
问题描述
我是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)
和
case Parsers.Success(r, n) => println(r)
和
import scala.util.parsing.combinator.Parsers.Success
但是我似乎无法编译它.我敢肯定我可能会遗漏一些明显的东西,但是我已经有一段时间了,而Google似乎没有很好的例子.
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.
谢谢!
推荐答案
您需要指定ParseResult
的完整路径,其中包括Parsers
实例.例如:
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.
这篇关于Scala中解析器成功的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!