Question abt Num

Artie Gold artiegold at austin.rr.com
Wed Oct 22 22:56:16 EDT 2003


Pratik Bhadra wrote:
> 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

Look at the RHS of the above.
[Hint: What is its type? And what are the types of `e1' and `e2'? 
And why would it be a valid expression?]

> opValue Sub e1 e2 = e1 - e2
> opValue Mul e1 e2 = e1 * e2
> opValue Div e1 e2 = e1 / e2
> opValue LT e1 e2  = e1 < e2

Similarly.

> 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?
> 
See above. I think you'll figure it out.

HTH,
--ag

PS - say `Hi' to Ham for me. ;-)

-- 
Artie Gold -- Austin, Texas
Oh, for the good old days of regular old SPAM.



More information about the Haskell mailing list