[Haskell-beginners] Arithmetic expression parsing problem

m00nlight dot_wangyushi at yeah.net
Mon Mar 30 06:22:20 UTC 2015


Dear Haskellers,

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



import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.Combinator
import Data.Functor

data Exp = Num Int
         | Add Exp Exp
         | Sub Exp Exp
         | Mul Exp Exp
         | Div Exp Exp
         | Pos Exp
         | Neg Exp

expr = buildExpressionParser table factor


table = [[op "*" (Mul) AssocRight, op "/" (Div) AssocRight]
        ,[op "+" (Add) AssocLeft, op "-" (Sub) AssocLeft]
        ,[prefix "-" (Neg), prefix "+" (Pos)]]
        where op s f assoc = Infix (f <$ string s) assoc
              prefix s f = Prefix (f <$ string s)


factor = between (char '(') (char ')') expr <|> (Num . read <$> many1 digit)

eval :: (Num a, Integral a) => Exp -> a
eval e = case e of
    Num x   -> fromIntegral x
    Pos a   -> eval a
    Neg a   -> negate $ eval a
    Add a b -> eval a   +   eval b
    Sub a b -> eval a   -   eval b
    Mul a b -> eval a   *   eval b
    Div a b -> eval a `div` eval b

solution :: (Num a, Integral a) => String -> a
solution = either (const (error "Did not parse")) eval . parse expr ""

The following is some test,



*Main> solution "-4/(2+3)"
0
*Main> solution "-4/(2-3)"
4
*Main> solution "-4/-2"
*** Exception: Did not parse
*Main> solution "16/-4"
*** Exception: Did not parse
*Main> solution "-16/4"
-4
*Main>

Can anyone teach me how to solve this?  Thanks in advanced.




--m00nlight


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150330/35b8ed6c/attachment.html>


More information about the Beginners mailing list