【问题标题】:Implementation of ~> and <~ parser combinators operators~> 和 <~ 解析器组合运算符的实现
【发布时间】:2013-11-26 16:53:51
【问题描述】:

Scala 的源代码解释了这些运算符:

~&gt; is a parser combinator for sequential composition which keeps only the right result.

&lt;~ is a parser combinator for sequential composition which keeps only the left result

我写了以下两个类。请注意,Daniel Spiewak 在这个主题上的出色 article 对我开始理解 Parser Combinators 帮助很大。

~&gt;

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
    }
}

&lt;~:

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

这对吗?

【问题讨论】:

    标签: scala parser-generator


    【解决方案1】:

    是的,你是对的。 StreamtoString 不是不可变的,您可以在 REPL 中验证:

    scala> val s = Stream(1,2,3,4,5,6,7,8)
    s: scala.collection.immutable.Stream[Int] = Stream(1, ?)
    
    scala> s(3)
    res5: Int = 4
    
    scala> s
    res6: scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, ?)
    

    【讨论】:

    • 谢谢。 Luigi,不是immutable,因为它s 的结构不能改变吗?但不是referentially transparent,因为调用s.toString 不会总是输出相同的结果?
    • Stream 本身当然是不可变的,只要您不将其 toString 视为核心功能,我不会。我认为您在技术上是正确的,“引用透明度”是函数是否总是为给定输入返回相同内容的正确术语,而“不变性”是数据结构/对象的属性。
    猜你喜欢
    • 2012-07-17
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多