
On Mon, Mar 30, 2015 at 02:22:20PM +0800, m00nlight wrote:
I am new to programming in haskell, recently I came up with an task to write an simple arithemtic evaluator in haskell. I try to write it using Text.Parsec, it can handle binary operation and some unary operation, but will give information of parsing error in some case. The following is my code
[..] Can anyone teach me how to solve this? Thanks in advanced.
Hello, first things first, I slightly modified your `solution` function, so it can fail with meaningful error messages solution :: (Num a, Integral a) => String -> a solution = either (error . show) eval . parse expr "" Then I added to `<?>` operators at the end of your parsing expression (again, for easier diagnostic). factor = between (char '(') (char ')') expr <|> (Num . read <$> many1 digit) <?> "factor" expr = buildExpressionParser table factor <?> "expr" Now the error message is: λ> solution "-4/-2" *** Exception: (line 1, column 4): unexpected "-" expecting factor So Parsec was expecting a "factor" element but found itself with '-'. The first alternative of factor is not what we want (an expression surrounded by parentheses). The second part should be it (a 'number'). Now it is easy to recognise the problem: `digit` only accepts digits and not '-' as a prefix. When parsing stuff, <?>, small functions and early testing (with hspec[1]) saved me much time and pain debugging. [1] http://hspec.github.io/