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