I'm trying out the parsec library and I'm not sure how to handle this basic task.
Suppose I have the following:
data Foo = A | AB
and I want the string "a" to be parsed as A
and "a b" AB
. If I just do this:
parseA :: parser Foo
parseA = do
reserved "a"
return A
parseAB :: parser Foo
parseAB = do
reserved "a"
reserved "b"
return AB
parseFoo :: parser Foo
parseFoo = parseA
<|> parseAB
then parseFoo
will parse "a b" as A
since parseA
doesn't care that there is non-whitespace still left after consuming the 'a'. How can this be fixed?
You need to change grammar to AB | A
and use try
from parsec, which gives lookahead capability to your parser.
This should work
parseFoo = try Parse AB <|> parse A