这是我的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
这是我的评估功能:
eval :: Ex a -> Integer
eval (I n) = n
eval (Add e1 e2) = eval e1 + eval e2
如何eval
和Variable
Def
答案 0 :(得分:1)
这是一个提示:
eval :: Ex a -> Integer
eval = eval' []
where eval' :: [(a, Integer)] -> Ex a -> Integer
eval' _ (I n) = n
-- etc
答案 1 :(得分:1)
更多提示可帮助您自己编写解决方案。
一些建议
lookup
类型列表上执行[(a,Ex a)]
,因此需要Eq a
约束。eval
函数应返回Nothing
,否则Just answer
。Variable a
个案例。这很简单,因为您需要在lookup
xs
lookup
并在评估后返回值,如果Nothing
成功,则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.
。代码变为
{{1}}