Reputation: 2079
Here's my ADT:
data Ex a = I Integer --integer
| Add (Ex a) (Ex a) --add
| Variable a --variable
| Def [(a, Ex a)] (Ex a) --defining local variables
And here's my evaluate function:
eval :: Ex a -> Integer
eval (I n) = n
eval (Add e1 e2) = eval e1 + eval e2
How do I continue eval
for Variable
and Def
?
Upvotes: 0
Views: 239
Reputation: 11218
Some more hints to help you write the solution yourself.
Some suggestions
lookup
on the list of type [(a,Ex a)]
and hence need Eq a
constraint on that.eval
function should return Nothing
otherwise Just answer
.Variable a
case. Which is very simple as you just need to lookup
a in xs
and return the value after evaluating it if lookup
succeeds else Nothing
.The code becomes
eval :: Eq a => Ex a -> Maybe Integer
eval = eval' []
where eval' :: Eq a => [(a, Ex a)] -> Ex a -> Maybe Integer
eval' _ (I n) = Just n
eval' xs (Add e1 e2) = liftA2 (+) (eval' xs e1) (eval' xs e2) -- liftA2 from Control.Applicative
eval' xs (Variable a) = -- write your code here
eval' xs (Def ys e) = eval' (ys ++ xs) e -- Think of the order in which you want to combine two binding if same named variable is present in both xs and ys.
Upvotes: 1
Reputation: 47072
Here's a hint:
eval :: Ex a -> Integer
eval = eval' []
where eval' :: [(a, Integer)] -> Ex a -> Integer
eval' _ (I n) = n
-- etc
Upvotes: 1