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.
You can use the ^?
combinator which accepts a partial function (Scaladoc):
def stored_val: Parser[String] = ident ^? {
case k if m.contains(k) => m(k)
}
I pushed a full example with tests to Github.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With