nkl
nkl

Reputation: 9

How to build Parser in Haskell

data Expr   = ExprNum Double -- constants
            | ExprVar String -- variables
            | ExprAdd Expr Expr
            | ExprSub Expr Expr
            | ExprNeg Expr -- The unary '-' operator
            | ExprMul Expr Expr
            | ExprDiv Expr Expr
            deriving Show

This is my user define data type. I want to handle arithmetic expression like (2+3 *4 - x) using above data types without using buildExpression parser. What can I do?

Please help me.It should handle operator precedence.

Upvotes: 0

Views: 332

Answers (1)

alternative
alternative

Reputation: 13012

Suppose we want to build an addsub level parser. We'd like to say that (ignoring actual returning of correct values and just focusing on the raw parsing)

addsub = muldiv >> oneOf "+-" >> muldiv

This doesn't really work. But we can left factor this as

addsub = muldiv >> addsub'
addsub' = many $ oneOf "+-" >> muldiv

Where we assume muldiv is a parser for just multiplication and division which you can write in a similar manner.

That is, instead of using the grammar

addsub = addsub (+-) muldiv | muldiv

We use the slightly more complicated, but actually usable by Parsec:

addsub = muldiv addsub'
addsub' = (+-) muldiv addsub' | Nothing

Which we can of course refactor the latter into a many which gives us a list of expressions that we would add. You could then convert that to whatever form you want, such as (Add a1 (Add a2 (Add a3))).

Upvotes: 3

Related Questions