【发布时间】:2013-11-26 16:53:51
【问题描述】:
Scala 的源代码解释了这些运算符:
~> is a parser combinator for sequential composition which keeps only the right result.
<~ is a parser combinator for sequential composition which keeps only the left result
我写了以下两个类。请注意,Daniel Spiewak 在这个主题上的出色 article 对我开始理解 Parser Combinators 帮助很大。
~>
class KeepRightParser[+A](left: =>Parser[A],
right: =>Parser[A]) extends Parser[A] {
def apply(s: Stream[Character]) = left(s) match {
case Success(_, rem) => right(rem)
case f: Failure => f
}
}
和<~:
class KeepLeftParser[+A](left: =>Parser[A],
right: =>Parser[A]) extends Parser[A] {
def apply(s: Stream[Character]) = left(s) match {
case Success(a, rem) => right(rem) match {
case Success(_, _) => Success(a, rem)
case f: Failure => f
}
case f: Failure => f
}
}
这是测试:
val s4 = Stream[Character]('f', 'o', 'o', 'b', 'a', 'r', 'b', 'u', 'z', 'z')
val krp = new KeepRightParser("foo", "bar")
println("~> test: " + krp(s4))
val klp = new KeepLeftParser("foo", "bar")
println("<~ test: " + klp(s4))
带输出:
~> test: Success(bar,Stream(b, ?))
<~ test: Success(foo,Stream(b, a, r, b, ?))
据我了解,第二个流显示的内容比它的 head 更多,因为需要读取 bar 以解析序列的后半部分。
这对吗?
【问题讨论】: