gpt4 book ai didi

scala - Parboiled2 解析器示例

转载 作者:行者123 更新时间:2023-12-04 16:47:12 26 4
gpt4 key购买 nike

我正在尝试从 parboiled2 中尝试这个例子:

scala> class MyParser(val input: org.parboiled2.ParserInput) 
extends org.parboiled2.Parser {
def f = rule { capture("foo" ~ push(42))
}
}
defined class MyParser

然后,我创建一个新的 MyParser,输入 "foo"

scala> new MyParser("foo").f
res11: org.parboiled2.Rule[shapeless.HNil,shapeless.::
[Int,shapeless.::[String,shapeless.HNil]]] = null

但返回值为null

如何从 REPL 运行这个简单的 f 规则

最佳答案

Parboiled 2 的 rule 是一个宏,使用 rule 定义的方法不打算在其他规则的上下文之外引用或调用运行()。因此,如果您有以下情况:

import org.parboiled2._

class MyParser(val input: ParserInput) extends Parser {
def f = rule { capture("foo" ~ push(42)) }
}

您可以像这样使用它(为清楚起见清理了类型):

scala>  new MyParser("foo").f.run()
res0: scala.util.Try[Int :: String :: HNil] = Success(42 :: foo :: HNil)

如果您不想要Try,您可以使用另一个delivery schemes .

关于scala - Parboiled2 解析器示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29223741/

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