gpt4 book ai didi

scala - ~> 和 <~ 解析器组合运算符的实现

转载 作者:行者123 更新时间:2023-12-02 03:40:47 25 4
gpt4 key购买 nike

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, ?))

据我了解,自 bar 以来,第二个流显示的不仅仅是它的头部需要阅读以解析序列的后半部分。

这是正确的吗?

最佳答案

是的,你是对的。 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, ?)

关于scala - ~> 和 <~ 解析器组合运算符的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20223164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com