Skip to content

Instantly share code, notes, and snippets.

@mrluanma
Created May 22, 2010 08:26
Show Gist options
  • Save mrluanma/409914 to your computer and use it in GitHub Desktop.
Save mrluanma/409914 to your computer and use it in GitHub Desktop.
-- File: exprparser.hs
-- This is from the Parsec documentation with minor modification.
module ExprParser where
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Language
lexer :: P.TokenParser ()
lexer = P.makeTokenParser haskellDef{reservedOpNames = ["*", "/", "+", "-"]}
whiteSpace = P.whiteSpace lexer
lexeme = P.lexeme lexer
symbol = P.symbol lexer
natural = P.natural lexer
parens = P.parens lexer
semi = P.semi lexer
identifier = P.identifier lexer
reserved = P.reserved lexer
reservedOp = P.reservedOp lexer
expr :: Parser Integer
expr = buildExpressionParser table factor <?> "expression"
table = [[op "*" (*) AssocLeft, op "/" div AssocLeft]
,[op "+" (+) AssocLeft, op "-" (-) AssocLeft]
]
where
op s f assoc
= Infix (do { reservedOp s; return f} <?> "operator") assoc
factor = parens expr
<|> natural
<?> "simple expression"
runLex :: Show a => Parser a -> String -> IO ()
runLex p input
= parseTest (do { whiteSpace
; x <- p
; eof
; return x
}
) input
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment