Question abt Num

Pratik Bhadra pratikb at cs.utexas.edu
Wed Oct 22 22:20:04 EDT 2003


Hi

I have a data type Expr for handling Expressions

data Expr = Lit1 Int | Lit2 Bool | Var String | BinOp Op Expr Expr

As you can see, I am trying to have an Expression have both Int and Bool
values so that I can work with both arithmetic (+,-,*,/) and
logical(and,or,<,<=,>,>=) operators.

What I am aiming at is to parse a line which contains an expression,
evaluate it and return the result. I am facing some problems in this
regard. When I write the evaluate function, the Haskell compiler refuses
to compile my code as it says, instance of Num Expr required. Any ideas
what I am supposed to do to fix that?

My evaluate code is as follows...

evaluate :: Expr -> Store -> Expr

evaluate ( Lit1 n ) st = n
evaluate ( Lit2 n ) st = n
evaluate ( Var v ) st = value st v  -- returns the value of v
evaluate ( BinOp op e1 e2 ) st = opValue op v1 v2
					where
						v1 = evaluate e1 st
						v2 = evaluate e2 st

opValue :: Op -> Expr -> Expr -> Expr
opValue Add e1 e2 = e1 + e2
opValue Sub e1 e2 = e1 - e2
opValue Mul e1 e2 = e1 * e2
opValue Div e1 e2 = e1 / e2
opValue LT e1 e2  = e1 < e2
opValue LE e1 e2  = e1 <= e2
opValue GT e1 e2  = e1 > e2
opValue GE e1 e2  = e1 >= e2
opValue And e1 e2 = e1 && e2
opValue Or e1 e2  = e1 || e2

Now I can't return an Int as I return a Bool at times and hence I return
an Expr. What does the error...instance of Num Expr or instance of
Fractional Expr required mean?

Thanks in advance!
Pratik



--------------------------------
Pratik Bhadra
Undergraduate Section Leader
The University of Texas at Austin
College of Natural Sciences
Junior
BS Computer Sciences
---------------------------------


More information about the Haskell mailing list