<div style="color:#000; font-size: 14px;font-family: arial;"><div>Hi Francesco,<br><br>Thanks for your explaination, so how can I modify the parser to handle this case?<br>Can you give me some more details of how to modify it? <br><br>Thanks in advanced.<br></div><div><br></div><div><br></div><div><br></div></div><div id="spnEditorSign" name="100"><div><div>--m00nlight<br></div></div></div><div><br></div><!-- jy5ContentSuffix --><div>在2015年03月30 15时05分, "Francesco Ariis"<fa-ml@ariis.it>写道:</div><blockquote id="isReplyContent" style="padding-left: 1ex; margin: 0px 0px 0px 0.8ex; border-left: 1px solid rgb(204, 204, 204);"><br>On Mon, Mar 30, 2015 at 02:22:20PM +0800, m00nlight wrote:<br>> I am new to programming in haskell, recently I came up with an task to<br>> write an simple arithemtic evaluator in haskell. I try to write it using<br>> Text.Parsec, it can handle binary operation and some unary operation,<br>> but will give information of parsing error in some case. The following<br>> is my code<br>> <br>> [..]<br>> Can anyone teach me how to solve this?  Thanks in advanced.<br><br>Hello,<br><br>first things first, I slightly modified your `solution` function, so it<br>can fail with meaningful error messages<br><br>    solution :: (Num a, Integral a) => String -> a<br>    solution = either (error . show) eval . parse expr ""<br><br>Then I added to `<?>` operators at the end of your parsing expression<br>(again, for easier diagnostic).<br><br>    factor = between (char '(') (char ')') expr<br>             <|> (Num . read <$> many1 digit) <?> "factor"<br><br>    expr = buildExpressionParser table factor <?> "expr"<br><br>Now the error message is:<br><br>    λ> solution "-4/-2"<br>    *** Exception: (line 1, column 4):<br>    unexpected "-"<br>    expecting factor<br><br>So Parsec was expecting a "factor" element but found itself with '-'.<br>The first alternative of factor is not what we want (an expression<br>surrounded by parentheses).<br>The second part should be it (a 'number'). Now it is easy to recognise<br>the problem: `digit` only accepts digits and not '-' as a prefix.<br><br><br>When parsing stuff, <?>, small functions and early testing (with<br>hspec[1]) saved me much time and pain debugging.<br><br><br>[1] http://hspec.github.io/<br></blockquote><br><br><span title="neteasefooter"><span id="netease_mail_footer"><span title="neteasefooter"><span id="netease_mail_footer"><a href="#" target="_blank"></a></span></span>
</span></span>