【问题标题】:Scala Parser Combinator compilation issue: failing to match multiple variables in caseScala Parser Combinator 编译问题:无法匹配多个变量以防万一
【发布时间】:2013-04-26 10:43:50
【问题描述】:

我正在学习如何使用 Scala Parser Combinators,顺便说一句,使用起来很有趣。

不幸的是,我遇到了编译错误。我已经阅读并重新创建了以下工作示例:http://www.artima.com/pins1ed/combinator-parsing.html

我已将代码简化为更简单的版本来演示我的问题。我正在研究可以解析以下示例的解析器

if a then x else y
if a if b then x else y else z

另外一点,条件可以有一个可选的“/1,2,3”语法

if a/1 then x else y
if a/2,3 if b/3,4 then x else y else z

所以我以下面的代码结束了

 def ifThenElse: Parser[Any] = 
    "if" ~> condition ~ inputList ~ yes ~> "else" ~ no 
 def condition: Parser[Any] = ident
 def inputList: Parser[Any] = opt("/" ~> repsep(input, ","))
 def input: Parser[Any] = ident
 def yes: Parser[Any] = "then" ~> result | ifThenElse
 def no: Parser[Any] = result | ifThenElse
 def result: Parser[Any] = ident

现在我想添加一些转换。我现在在第二个 ~ 的情况下得到一个编译错误:

  def ifThenElse: Parser[Any] =
    "if" ~> condition ~ inputList ~ yes ~> "else" ~ no ^^ {
      case c ~ i ~ y ~ n => null
                 ^ constructor cannot be instantiated to expected type; found : SmallestFailure.this.~[a,b] required: String

当我将代码更改为

   "if" ~> condition ~ inputList ~ yes ~> "else" ~ no ^^ {
      case c ~ i => println("c: " + c + ", i: " + i)                 

我预计它不会编译,但它确实编译了。我以为每个子句都需要一个变量。当执行(使用 parseAll)解析“if a then b else c”时,会产生“c: else, i: c”。所以看起来 c 和 i 是字符串的尾部。

我不知道它是否重要,但是示例教程似乎都没有匹配两个以上变量的示例,而这是匹配四个

【问题讨论】:

  • 我很抱歉。提出这个问题让我有足够的信息来自己解决它。我会删除它,但不能这样做。我想我有 ~> 周围的 else 错误。如果我只使用 "if" ~> 条件 ~ inputList ~ yes ~ "else" ~ no ^^ { case c ~ i ~ y ~ e ~ n => println("c: " + c + " i: " + i ) 然后一切正常。 :(
  • 您可以发布自己问题的答案(作为答案,而不仅仅是作为评论) - 这将帮助遇到相同问题的其他人。
  • 我会尽快超时让我这样做

标签: parsing scala parser-combinators


【解决方案1】:

您不必匹配"else":

def ifThenElse: Parser[Any] =
    "if" ~> condition ~ inputList ~ (yes <~ "else") ~ no ^^ {
      case c ~ i ~ y ~ n => null
    }

按预期工作。

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多