Last active
August 29, 2015 13:57
-
-
Save scturtle/9408629 to your computer and use it in GitHub Desktop.
calc with parsec
This file contains 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
import Text.Parsec | |
import Text.Parsec.Expr | |
import Text.Parsec.Language (emptyDef) | |
import Text.Parsec.String (Parser) | |
import qualified Text.Parsec.Token as P | |
lexer = P.makeTokenParser emptyDef | |
parens = P.parens lexer | |
number :: Parser Double | |
number = do res <- P.naturalOrFloat lexer | |
case res of | |
Left n -> return $ fromInteger n | |
Right f -> return f | |
table = [[op "*" (*) AssocLeft, op "/" (/) AssocLeft] | |
,[op "+" (+) AssocLeft, op "-" (-) AssocLeft]] | |
where op s f assoc = Infix (do string s; return f) assoc | |
expr :: Parser Double | |
expr = buildExpressionParser table factor | |
where factor = parens expr <|> number | |
eval = parse expr "" | |
main = interact (unlines . map (show . eval) . lines) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment