本文介绍了Scala:我可以将组合器解析器微调为本地贪婪吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在组合器解析器中表达的语言不明确.有没有办法使某些表达在局部上是贪婪的?这是我的意思的例子.
Suppose I have an ambiguous language expressed in combinator parser. Is there a way to make certain expressions locally greedy? Here's an example of what I mean.
import scala.util.parsing.combinator._
object Example extends JavaTokenParsers {
def obj: Parser[Any] = (shortchain | longchain) ~ anyrep
def longchain: Parser[Any] = zero~zero~one~one
def shortchain: Parser[Any] = zero~zero
def anyrep: Parser[Any] = rep(any)
def any: Parser[Any] = zero | one
def zero: Parser[Any] = "0"
def one: Parser[Any] = "1"
def main(args: Array[String]) {
println(parseAll(obj, args(0) ))
}
}
编译后,可以如下运行:
After compiling, I can run it as follows:
$ scala Example 001111
[1.7] parsed: ((0~0)~List(1, 1, 1, 1))
我想以某种方式指示的第一部分是局部贪婪并与longchain
匹配.如果我改变顺序,它会匹配longchain
,但这不是因为贪婪.
I would like to somehow instruct the first part of obj
to be locally greedy and match with longchain
. If I switch the order around, it matches the longchain
, but that's not because of the greediness.
def obj: Parser[Any] = (longchain | shortchain) ~ anyrep
推荐答案
使用|||
:
object Example extends JavaTokenParsers {
def obj: Parser[Any] = (shortchain ||| longchain) ~ anyrep
def longchain: Parser[Any] = zero~zero~one~one
def shortchain: Parser[Any] = zero~zero
def anyrep: Parser[Any] = rep(any)
def any: Parser[Any] = zero | one
def zero: Parser[Any] = "0"
def one: Parser[Any] = "1"
def main(args: Array[String]) {
println(parseAll(obj, args(0) ))
}
}
scala> Example.main(Array("001111"))
[1.7] parsed: ((((0~0)~1)~1)~List(1, 1))
这篇关于Scala:我可以将组合器解析器微调为本地贪婪吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!