Errors and failures in Scala Parser Combinators

百般思念 提交于 2019-12-05 07:59:05

In this case you want err, not failure, since if the first parser in a disjunction fails you'll just move on to the second, which isn't what you want.

The other issue is that ^^ is the equivalent of map, but you want flatMap, since err("whatever") is a Parser[Nothing], not a Nothing. You could use the flatMap method on Parser, but in this context it's more idiomatic to use the (completely equivalent) >> operator:

object TestFail extends JavaTokenParsers {
  def test: Parser[String] =
    "hello" ~> "world" >> (x => err(s"Can't say hello to the $x!")) |
    "hello" ~ ident ^^ { case "hello" ~ id => s"hi, $id" }
}

Or, a little more simply:

object TestFail extends JavaTokenParsers {
  def test: Parser[String] =
    "hello" ~ "world" ~> err(s"Can't say hello to the world!") |
    "hello" ~ ident ^^ { case "hello" ~ id => s"hi, $id" }
}

Either approach should do what you want.

You could use ^? method:

object TestFail extends JavaTokenParsers {
  def test: Parser[String] =
    "hello" ~> ident ^? (
      { case id if id != "world" => s"hi, $id" },
      s => s"Should not use '$s' here."
  )
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!