Skip to content

Instantly share code, notes, and snippets.

@553224019
Created April 5, 2019 13:40
Show Gist options
  • Select an option

  • Save 553224019/1b573f3c4dcea59c8933b0e496699fb6 to your computer and use it in GitHub Desktop.

Select an option

Save 553224019/1b573f3c4dcea59c8933b0e496699fb6 to your computer and use it in GitHub Desktop.
module Calculator (evaluate) where
import Text.ParserCombinators.Parsec
import Data.Either (fromRight)
-- evaluate
evaluate :: String -> Double
evaluate s = fromRight (error "Parse Error!") $ parse expr "" s
-- parse expression
expr :: Parser Double
expr = (parens expr <|> num) `chainl1` multop `chainl1` addop
where parens = between (symbol "(") (symbol ")")
addop, multop :: Parser (Double -> Double -> Double)
addop = try (symbol "+" >> return (+)) <|> try (symbol "-" >> return (-))
multop = try (symbol "*" >> return (*)) <|> try (symbol "/" >> return (/))
-- parse num and symbol
num :: Parser Double
num = do
dx <- many1 $ oneOf "0123456789."
return $ read dx
symbol :: String -> Parser ()
symbol s = spaces >> string s >> spaces
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment