在 Scala 解析器组合器库中多次使用 ~> 和 <~
Using ~> and <~ several times in Scala parser combinator library
我正在使用 Scala 解析器组合器库来解析属于术语重写器库的术语。这是给我带来问题的代码:
def parser: Parser[(Map[String,Operation],List[Rule])] =
"section signature\n" ~> signature <~ "end signature" ~
"section rules\n" ~> rules <~ "end rules" ^^ {
case s ~ rs => (s,rs)
}
目的是仅对部分函数中的签名和规则进行模式匹配。但是,上面的代码给出了编译错误,我能做的最好的是:
def parser: Parser[(Map[String,Operation],List[Rule])] =
"section signature\n" ~> signature ~ "end signature" ~
"section rules\n" ~ rules <~ "end rules" ^^ {
case s ~ "end signature" ~ "section rules\n" ~ rs => (s,rs)
}
有没有办法去掉 "end signature" ~ "section rules\n" 部分?
我通常会这样做:
("section signature\n" ~> signature <~ "end signature") ~
("section rules\n" ~> rules <~ "end rules")
顺便说一句:显式 \n
看起来很可疑。真的需要吗?同样,硬编码的 space 看起来也很奇怪。如果输入包含 "section signature"
或 "section\n signature"
怎么办?如果一行以 space 结尾怎么办(讨厌,因为没有特殊的文本编辑器设置是不可见的)?解析器真的必须在 whitespace 的每个微小变化上都出现灾难性的失败吗?
我正在使用 Scala 解析器组合器库来解析属于术语重写器库的术语。这是给我带来问题的代码:
def parser: Parser[(Map[String,Operation],List[Rule])] =
"section signature\n" ~> signature <~ "end signature" ~
"section rules\n" ~> rules <~ "end rules" ^^ {
case s ~ rs => (s,rs)
}
目的是仅对部分函数中的签名和规则进行模式匹配。但是,上面的代码给出了编译错误,我能做的最好的是:
def parser: Parser[(Map[String,Operation],List[Rule])] =
"section signature\n" ~> signature ~ "end signature" ~
"section rules\n" ~ rules <~ "end rules" ^^ {
case s ~ "end signature" ~ "section rules\n" ~ rs => (s,rs)
}
有没有办法去掉 "end signature" ~ "section rules\n" 部分?
我通常会这样做:
("section signature\n" ~> signature <~ "end signature") ~
("section rules\n" ~> rules <~ "end rules")
顺便说一句:显式 \n
看起来很可疑。真的需要吗?同样,硬编码的 space 看起来也很奇怪。如果输入包含 "section signature"
或 "section\n signature"
怎么办?如果一行以 space 结尾怎么办(讨厌,因为没有特殊的文本编辑器设置是不可见的)?解析器真的必须在 whitespace 的每个微小变化上都出现灾难性的失败吗?