我是 Scala 的新手,一直在尝试使用其出色的组合器解析器库。我一直在尝试编译此代码:
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)
}
...
但我不断收到这些错误:
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)
我尝试了很多不同的事情,例如:
case Parsers#Success(r, n) => println(r)
和
case Parsers.Success(r, n) => println(r)
和
import scala.util.parsing.combinator.Parsers.Success
但我似乎无法编译它。我敢肯定,我可能遗漏了一些明显的东西,但我已经研究了一段时间,而 google 似乎没有任何很好的例子。
谢谢!
请您参考如下方法:
您需要为 ParseResult 指定完整路径,其中包括您的 Parsers实例。例如:
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)
}
请注意,如果您想要一些额外的语法便利,您也可以导入这些:
import parser.{ Error, Failure, Success }
现在您的原始版本将按预期工作。




