简体   繁体   English

具有可选值的解析器组合器^^

[英]Parser Combinator ^^ with Optional Values

I'm trying to modify an example from DSLs in Action . 我正在尝试修改Action中的DSL示例。

Originally, this code was used to parse items followed by account . 原来,这个代码是用来解析items ,然后account

  lazy val order: Parser[Order] = 
    items ~ account_spec ^^ {
      case i ~ a => Order(i, a)
    }

The following text could be parsed with the above parser: 可以使用上面的解析器解析以下文本:

(100 IBM shares to buy at max 45) for account "A1234
------------- item -------------  ------ account ----

But, I'd like to add FOO and an optional not values to the parser: 但是,我想在解析器中添加FOO和一个可选的not值:

  lazy val order: Parser[Order] = 
    items <~ "FOO" ~> ("not"?) ~ account_spec ^^ {
      case i ~ n ~ a => println(n); Order(i, a)
    }

FOO must follow account and, optionally, not will follow. FOO必须遵循account并且可选择not遵循account

Example: 例:

(100 IBM shares to buy at max 45) FOO not for account "A1234
---------- item ------------------ --- --- ------ account ----

However, the above code gives me this compile-time error: 但是,上面的代码给了我这个编译时错误:

[WARNING] ....\OrderDsl.scala:19: error: constructor cannot be instantiated to 
expected type;
[WARNING]  found   : ch8.trading.semantic.dsl.OrderDsl.~[a,b]
[WARNING]  required: ch8.trading.semantic.dsl.AST.Items
[WARNING]       case i ~ n ~ a => println(n); Order(i, a)
[WARNING]                  ^

How can I modify the case statement to support parsing an optional "not" value? 如何修改case语句以支持解析可选的 “not”值?

a <~ "FOO" ~> b means "ignore results of parsers "FOO" and b and return the result of a ". a <~ "FOO" ~> b的意思是“忽略的解析器结果"FOO"b ,并返回的结果a ”。

Rewrite your method like this: 像这样重写你的方法:

lazy val order: Parser[Order] = 
  items ~ opt("FOO") ~ opt("not") ~ account_spec ^^ {
    case i ~ _ ~ n ~ a => println(n); Order(i, a)
  }

General mnemonic for ~> and <~ : you can ignore from start to operator or from operator to end, but not the middle part of expression. ~><~常规助记符:您可以从开始到操作符或从操作符到结尾忽略,但不能忽略表达式的中间部分。

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

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