Separating different types of terms during parsing

I have two parsers for different types of terms.

a :: Parser A
b :: Parser B

I have a data type representing a sequence of these terms.

data C = C [A] [B]

If my input is a sequence of mixed terms, then what is the way to write c :: Parser Cto divide Aby Bs while preserving their order? For example, given these definitions:

data A = A Char
data B = B Char
a = A <$> oneOf "Aa"
b = B <$> oneOf "Bb"

"abAbBBA"will be analyzed by sequences aAAand bbBB. I have a feeling that I need to use StateT, but I'm not sure about the specifics and just need a push in the right direction.

+3
source share
2 answers

, Either A B, partitionEithers, , C .

c :: Parser C
c = uncurry C . partitionEithers <$> many ((Left <$> a) <|> (Right <$> b))
+7

, partitionEithers Data.Either, , ...

c :: Parser C
c = (post . partitionEithers ) <$> many1 aORb
  where
    post (as,bs) = C as bs


aORb :: Parser (Either A B)
aORb = (Left <$> a) <|> (Right <$> b)

-

!

+4

All Articles