如何评估由ADT构建的表达式

时间:2012-10-17 09:48:12

标签: haskell functional-programming

这是我的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

如何evalVariable

继续Def

2 个答案:

答案 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}}