This is my code:
expr :: Parser Integer
expr = buildExpressionParser table factor <?> "expression"
table :: [[ Operator Char st Integer ]]
table = [
[ op "*" (*) AssocLeft],
[ op "+" (+) AssocLeft]
]
where
op s f assoc = Infix (do { string s ; return f }) assoc
factor = do { char '(' ; x <- expr ; char ')' ; return x }
<|> number
<?> "simple expression"
number :: Parser Integer
number = do { ds <- many1 digit; return read(ds))) } <?> "number"
This works perfectly with expressions like this: (10+10) * 10. But I have a problem with the following: 10 +10) This has to return a parsing error (just 1 parenthesis at the end), but instead it returns 20.
How to fix this?
Thanks!
You'll need to use the eof
parser to make sure you've read the whole input:
myParser = do
parsed <- expr
eof
return parsed
If you're using Control.Applicative
this can be simplified to:
myParser = expr <* eof