I am looking for a function to dynamically combine Scala Parser Combinators. For example, if I want to do it statically I can write:
def aDirective: Parser[String] = "a" ^^ { case _ => "a" }
def bDirective: Parser[String] = "b" ^^ { case _ => "b" }
def combinedDirective: Parser[List[String]] =
aDirective ~ bDirective ^^ { case a ~ b => List(a, b) }
However rather than coding this statically I want to be able to do this dynamically, for the purposes of generating combinations of parsers.
For example:
def aDirective: Parser[String] = "a" ^^ { case _ => "a" }
def bDirective: Parser[String] = "b" ^^ { case _ => "b" }
def combinedDirective: Parser[List[String]] =
combine(List(aDirective, bDirective))
def combine(parsers: List[Parser[T]): Parser[List[T]] = ???
I think I need to go from a List of parsers to a Parser of List of Results. So I have attempted to write a signature for a function named combine
.
At the moment I cannot figure out how to implement the combine
function. Whichever way I attempt it, it seems to be fraught with problems that I cannot think how to solve at the moment. For example how do I construct an initial parser for a fold? I have tried to experiment with various foldLeft
and reduceLeft
constructs, but cannot seem to quite get there.
I am using Scala 2.11. Any ideas?