calculator-0.1.5.2: src/Model/Arithmetic.hs
module Model.Arithmetic (modelEval) where
--------------------------------------------------------------------------------
import Calculator.Parser.Base (parseNumber)
import Calculator.Prim.Base (Number)
--------------------------------------------------------------------------------
import Control.Applicative ((<*))
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
--------------------------------------------------------------------------------
modelEval :: String -> String
modelEval inp = case parse (expr <* eof) "Expression" inp of
Left _ -> ""
Right n -> show n
--------------------------------------------------------------------------------
expr :: Parser Number
expr = buildExpressionParser table factor <?> "Expression"
--------------------------------------------------------------------------------
table :: [[ Operator Char st Number ]]
table = [ [ op "^" (**) AssocRight ]
, [ op "*" (*) AssocLeft, op "/" (/) AssocLeft ]
, [ op "+" (+) AssocLeft, op "-" (-) AssocLeft ]
]
where op s f = Infix (string s >> return f)
--------------------------------------------------------------------------------
parseFactor :: Parser Number
parseFactor = do
_ <- char '('
x <- expr
_ <- char ')'
return x
--------------------------------------------------------------------------------
factor :: Parser Number
factor = parseFactor <|> parseNumber
--------------------------------------------------------------------------------