Last active
October 12, 2016 02:38
-
-
Save alogic0/cab6646e7b5c115735d62f7ad86c752c to your computer and use it in GitHub Desktop.
FutureLearn Haskell 2016, Parsing Text, Expression parsers
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
import Text.ParserCombinators.Parsec | |
import Text.ParserCombinators.Parsec.Expr | |
import qualified Text.ParserCombinators.Parsec.Token as P | |
import Text.ParserCombinators.Parsec.Language | |
import Control.Monad (liftM) | |
lexer = P.makeTokenParser emptyDef | |
parens = P.parens lexer | |
natural = P.natural lexer | |
reservedOp = P.reservedOp lexer | |
data Expr = | |
MkConst Integer | |
| MkOpExpr String Expr Expr | |
| MkPrefixOpExpr String Expr | |
deriving Show | |
expr_parser :: Parser Expr | |
expr_parser = buildExpressionParser optable term <?> "expression" | |
optable = | |
let | |
op name assoc = | |
Infix ( do { reservedOp name; | |
return (MkOpExpr name) } ) assoc | |
prefix name = | |
Prefix ( | |
reservedOp name >> | |
return (MkPrefixOpExpr name) ) | |
in | |
[ [ op "*" AssocLeft, op "/" AssocLeft, op "%" AssocLeft ] | |
, [ op "+" AssocLeft, op "-" AssocLeft ], [ prefix "-" ] ] | |
term = parens expr_parser | |
<|> liftM MkConst natural |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of running: