解析器组合器使用可选解析器处理交替

时间:2021-01-28 04:19:09

标签: scala parser-combinators

我有一个 Parser[Option[X]] 类型的解析器 p 和另一个 Parser[Y] 类型的 q 。 (XY 是具体类型,但这在这里并不重要)。

我想以这样的方式组合它们,结果解析器返回一个 Parser[Either[X, Y]]。如果 p 产生 Some(x) 或者,如果失败,它将以 Right 成功,则该解析器将在 Left(x) (y) 如果 q 产生一个 y。否则,它将失败。输入将在成功的情况下被消耗,但在不成功的情况下不会被消耗。

我很感激这方面的任何帮助,因为我不太清楚如何使它工作。

1 个答案:

答案 0 :(得分:0)

休息后多一点毅力,我能够解决这个问题。我认为我的解决方案不是最优雅的,希望得到反馈:

def compose[X, Y](p: Parser[Option[X]], q: Parser[Y]): Parser[Either[X, Y]] = Parser {
  in =>
    p(in) match {
      case s@this.Success(Some(_), _) => s map (xo => Left(xo.get))
      case _ => q(in) match {
        case s@this.Success(_, _) => s map (x => Right(x))
        case _ => this.Failure("combine: failed", in)
      }
    }
}

implicit class ParserOps[X](p: Parser[Option[X]]) {
  def ?|[Y](q: => Parser[Y]): Parser[Either[X, Y]] = compose(p, q)
}

// Example of usage
def anadicTerm: Parser[AnadicTerm] = (maybeNumber ?| anadicOperator) ^^ {
  case Left(x: Number) => debug("anadicTerm (Number)", AnadicTerm(Right(x)))
  case Right(x: String) => debug("anadicTerm (String)", AnadicTerm(Left(x)))
}
相关问题