Skip to content

Instantly share code, notes, and snippets.

@scturtle
Last active August 29, 2015 13:57
Show Gist options
  • Save scturtle/9408629 to your computer and use it in GitHub Desktop.
Save scturtle/9408629 to your computer and use it in GitHub Desktop.
calc with parsec
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