-1

I have those info on my haskell code:

data Symtable a = General a | Stack a

class Evaluable e where
eval :: (Num a, Ord a) => (Ident -> Maybe a) -> (e a) -> (Either String a)
typeCheck :: (Ident -> String) -> (e a) -> Bool

instance (Num a, Ord a) => Evaluable (NExpr a) where
eval f f2 = Left ("Undefined variable: ") --to make the code compilable
typeCheck f f2 = True --to make the code compilable

The thing is, eval function returns the evaluation of a numeric expression (for example 3 + 5, or x + 3), therefore I have to check the value of X on the symtable data but I haven't got it referenced on this function (I cannot edit the function header). How can I do it?

ident = string and Nexpr:

data NExpr n = Const n |
            Var Ident |
            Plus (NExpr n) (NExpr n) |
            Minus (NExpr n) (NExpr n) |
            Times (NExpr n) (NExpr n)
duplode
  • 33,731
  • 7
  • 79
  • 150

1 Answers1

2

The first arugment to eval is a function that will look up the value of a name found in an expression. You ignore it when evaluating a Const value, use it when evaluating a Var value, and just pass it along to the recursive calls for the other cases.

instance (Num a, Ord a) => Evaluable (NExpr a) where
  eval _ (Const n) = Right n
  eval lookup (Var x) = case lookup x of
                          Nothing -> Left ("Undefined variable: " ++ x)
                          Just y -> Right y

  eval lookup (Plus left right) = (+) <$> eval lookup left <*> eval lookup right
  -- etc
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    This also requires some changes to the `class Evaluable`, otherwise it involves `NExpr a b` which is a kind error. – chi Dec 05 '16 at 18:05
  • it says: couldn't match type 'e' with NExpr' 'e' is a rigid type variable bound by ... eval::... expected e a actual Nexpr a – Daniel Roca Lopez Dec 05 '16 at 18:24