Arithmetic evaluation: Difference between revisions

Line 2,175:
 
=={{header|Haskell}}==
<lang haskell>import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.Parsec.Combinator
import Data.Functor
 
data Exp = Num Int
Line 2,188 ⟶ 2,190:
table = [[op "*" (Mul) AssocLeft, op "/" (Div) AssocLeft]
,[op "+" (Add) AssocLeft, op "-" (Sub) AssocLeft]]
where op s f assoc = Infix (dof <$ string s; return f) assoc
 
factor = between do (char '(') ;(char x')') expr <-|> expr(Num ;. charread '<$> many1 digit)'
return x
<|> do ds <- many1 digit
return $ Num (read ds)
 
evaluateeval :: (Num x)a => Exp fromIntegral-> xa
eval e = case e of
evaluate (Add a b) = (evaluate a) + (evaluate b)
Num x -> fromIntegral x
evaluate (Sub a b) = (evaluate a) - (evaluate b)
evaluate (Mul Add a b) =-> (evaluateeval a) *+ (evaluateeval b)
evaluate (Div Sub a b) =-> (evaluateeval a) `div` (evaluate - eval b)
Mul a b -> eval a * eval b
Div a b -> eval a `div` eval b
 
solution exp:: =Num casea parse expr=> []String exp-> ofa
solution = either (const (error "Did not parse")) eval . parse expr ""</lang>
Right expr -> evaluate expr
Left _ -> error "Did not parse"</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
Anonymous user