I'm using scala parser combinator library to parse terms belonging to a term-rewriter library. Here is the code that is giving me problems:
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)
}
The intention is to pattern match onlythe signature and rules in the partial function. However, the above code gives a compile error and the best I can do is:
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)
}
Is there a way to get rid of "end signature" ~ "section rules\n" part?
I'd usually do something like this:
("section signature\n" ~> signature <~ "end signature") ~
("section rules\n" ~> rules <~ "end rules")
By the way: the explicit \n
looks suspicious. Is it really needed? Likewise, the hard-coded spaces also look strange. What if the input contains "section signature"
or "section\n signature"
? What if a line ends with a space (nasty, because invisible without special text editor settings)? Does the parser really have to fail catastrophically on every minor variation of the whitespace?