Search code examples
parsinghaskellmegaparsec

Haskell - intersperse a parser with another one


I have two parsers parser1 :: Parser a and parser2 :: Parser a.

I would like now to parse a list of as interspersing them with parser2

The desired signature is something like

interspersedParser :: Parser b -> Parser a -> Parser [a]

For example, if Parser a parses the 'a' character and Parser b parser the 'b' character, then the interspersedParser should parse

""
"a"
"aba"
"ababa"
...

I'm using megaparsec. Is there already some combinator which behaves like this, which I'm currently not able to find?


Solution

  • In parsec there is a sepBy parser which does that. The same parser seems to be available in megaparsec as well: https://hackage.haskell.org/package/megaparsec-4.4.0/docs/Text-Megaparsec-Combinator.html