0
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.

2
  • Is there a reason we can't use buildExpressionParser? I assume this means you are using parsec. Do you know how to left-factor your grammar so that it is actually valid? Commented Oct 27, 2014 at 13:13
  • "buildExpression parser" probably refers to this Parsec module. Commented Aug 14, 2015 at 0:37

1 Answer 1

3

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))).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.