实施〜>和<〜parser组合子运算符

时间:2013-11-26 16:53:52

标签: scala parser-generator

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来解析序列的后半部分。

这是对的吗?

1 个答案:

答案 0 :(得分:1)

是的,你是对的。 Stream的{​​{1}}不是不可变的,因为您可以在REPL中验证:

toString