Parsing challenges – expressions revisited
In this section, we’ll revisit the parser for simple arithmetic expressions, now using Parsec. We explore several variations and extensions, consolidate earlier lessons, and handle new challenges.
As our starting point, consider again the simple type for arithmetic expressions:
data Expr = Lit Int | Plus Expr Expr
We could write a very native parser for it that follows the structure of the data type definition:
exprP = literalP <|> sumP literalP = Lit <$> number sumP = do x <- exprP plus y <- exprP pure (Plus x y)
When used naively, the parser does not consume all the input:
*Main> parse exprP "1+2" Right (Lit 1)
To amend this, we have to check for the end of the file:
*Main> parse (exprP <...