简体   繁体   English

Scala解析器组合器

[英]Scala Parser Combinator

I am trying to write a Scala Parser combinator for the following input. 我正在尝试为以下输入编写一个Scala分析器组合器。

The input can be 输入可以是

  • 10 10
  • (10) (10)
  • ((10))) (((10)))
  • (((10))) ((((10)))

Here the number of brackets can keep on growing. 在这里,括号的数量可以继续增长。 but they should always match. 但它们应该始终匹配。 So parsing should fail for ((((10))) 因此对于((((10)))解析应该失败

The result of parsing should always be the number at the center 解析的结果应该始终是中间的数字

I wrote the following parser 我写了下面的解析器

import scala.util.parsing.combinator._
class MyParser extends RegexParsers {
  def i = "[0-9]+".r ^^ (_.toInt)
  def n = "(" ~ i ~ ")" ^^ {case _ ~ b ~ _ => b.toInt}
  def expr = i | n
}
val parser = new MyParser
parser.parseAll(parser.expr, "10")
parser.parseAll(parser.expr, "(10)")

but now how do I handle the case where the number of brackets keep growing but matched? 但是现在我该如何处理括号数量不断增加但匹配的情况?

Easy, just make the parser recursive: 简单,只需使解析器递归即可:

class MyParser extends RegexParsers {
  def i = "[0-9]+".r ^^ (_.toInt)
  def expr: Parser[Int] = i | "(" ~ expr ~ ")" ^^ {case _ ~ b ~ _ => b.toInt}
}

(but note that scala-parser-combinators has trouble with left -recursive definitions: Recursive definitions with scala-parser-combinators ) (但请注意,scala-parser-combinators在使用 递归定义时遇到麻烦: 使用scala-parser-combinators的递归定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM