I’ve got an example from documentation for Text.Parsec.Expr.
expr = buildExpressionParser table term
<?> "expression"
term = parens expr
<|> natural
<?> "simple expression"
table = [ [prefix "-" negate, prefix "+" id ]
, [postfix "++" (+1)]
, [binary "*" (*) AssocLeft, binary "/" (div) AssocLeft ]
, [binary "+" (+) AssocLeft, binary "-" (-) AssocLeft ]
]
I’d tried to add postfix -- operation and changed the second line for table to
, [postfix "++" (+1), postfix "--" (subtract 1)]
Now
runParser expr () "expr" "1--"
give me Right 1 in ghci.
Why I got it and how to provide postfix (--)?
"--1"gets parsed as[prefix "-", prefix "-", number 1]and evaluated asnegate (negate 1)which yields 1.To get a postfix(--), doesrunParser expr () "expr" "1--"not give you a postfix--?The parse seems to not consume the entire input. I can’t tell why, though,yields
as desired here.
The problem with
natural = P.natural lexeris that it is defined asand
where comments count as whitespace. Now, the line comments in Haskell start with
--, hence withnatural = P.natural lexer, thenaturalconsumes the entire string"1--". To make--usable as a postfix operator, you have to choose a language definition where that is not a comment starter. For example, you can modifyhaskellDefperor redefine the
whiteSpaceparser.