如何使 scala 解析器失败
所以我有这样的事情:
class MyParser extends JavaTokenParsers {
var m = new HashMap[String,String]
def store = ("var" ~> ident "=") ~ ident ^^ {
case k ~ v => m += k -> v
}
def stored_val = ident ^^ {
case k => m(k)
}
}
我的问题是我真正想做的是让解析器stored_val失败,以便其他解析器有机会匹配输入。但现在发生的情况是,当地图找不到该值时,它会抛出异常。
我尝试像这样实现stored_val:
def stored_val = ident => {
case k => if (m.contains(k)) m(k) else failure("identifier not found")
}
但问题是失败返回Parser[Nothing],它是与String不同的类型。
so I have something like this:
class MyParser extends JavaTokenParsers {
var m = new HashMap[String,String]
def store = ("var" ~> ident "=") ~ ident ^^ {
case k ~ v => m += k -> v
}
def stored_val = ident ^^ {
case k => m(k)
}
}
And my problem is that what I really want to do is have the parser stored_val fail so that other parsers have the chance to match the input. But what happens now is that the map throws when it can't find the value.
I tried implementing stored_val like this:
def stored_val = ident => {
case k => if (m.contains(k)) m(k) else failure("identifier not found")
}
But the problem with that is failure returns Parser[Nothing] which is a different type than String.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用接受部分函数的
^?
组合器 (Scaladoc):我推送了 完整示例 测试到Github。
You can use the
^?
combinator which accepts a partial function (Scaladoc):I pushed a full example with tests to Github.
如果您想检查正则表达式之外的字符内容,您可能需要查看
StandardTokenParser
。尤其,编辑:
有关标准令牌解析器的示例,请查看 Jim McBeath 关于 Scala 解析器的文章组合器。我对第一个示例进行了快速修改以演示
elem
。这是一个简单的解析器,只需要奇数的和:将上面的内容保存为
ExpressionParser.scala
并将其加载到 REPL 中,如下所示:If you want to check the content of the characters beyond regex, you might want to check out
StandardTokenParser
. In particular,Edit:
For examples of Standard Token Parser, check out Jim McBeath's article on Scala Parser Combinators. I made a quick modification to the first example to demonstrate
elem
. It's a simple parser that only takes sum of odd numbers:Save the above as
ExpressionParser.scala
and load it into REPL as follows: