Created
April 5, 2019 13:40
-
-
Save 553224019/1b573f3c4dcea59c8933b0e496699fb6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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