制作类型:添加数据类型和不匹配类型的评估器 [英] making types: Add data type and evaluator that is of an unmatched type
问题描述
我添加了|点亮Int和|将Exp与数据评估一起添加到如下所示的数据类型中.但是我收到错误消息无法将预期的类型"Var"与实际类型"Int"匹配".
I have added | Lit Int and | Add Exp Exp to the data type as seen below, along with the evaluation. However I get an error "Couldn't match expected type ‘Var’ with actual type ‘Int’".
data Exp = V Var
| B Bool
| L Exp
| A Exp Exp
| Lit Int
| Add Exp Exp
data Var = VZ |VS Var
eval:: Exp -> Var
eval (Lit n) = n
eval (Add e1 e2) = eval e1 + eval e2
如何将Int和Add与评估一起添加到数据类型中,但按原样维护以下代码.这可能吗?
How can I add Int and Add to the data type, along with the evaluation, but maintain the following code as is. Is this possible?
data Exp = V Var
| B Bool
| L Exp
| A Exp Exp
data Var = VZ |VS Var
我已经添加了一个实例来解决此问题,如下所示,但是现在我出现了错误实例声明中不允许出现模式绑定(简单变量除外):Add e1 e2 =(Lit e1)+(Lit e2)
I have added an instance to resolve this, as seen below, but now I have the error "Pattern bindings (except simple variables) not allowed in instance declaration: Add e1 e2 = (Lit e1) + (Lit e2)":
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
data Exp = V Var
| B Bool
| L Exp
| A Exp Exp
| Lit Int
| Add Exp Exp
data Var = VZ |VS Var
eval:: Exp -> Var
eval (Lit n) = n
eval (Add e1 e2) = eval e1 + eval e2
instance Num Var where
Lit e = e
instance Num Var where
Add e1 e2 = (Lit e1) + (Lit e2)
推荐答案
您似乎在此过程中感到困惑.我相信 Var
表示 De Bruijn中的免费变量符号.您缺少值的编码.这可能看起来像是模糊的
You seem to have gotten mixed up along the way. I believe Var
represents a free variable in De Bruijn notation. You're missing an encoding of values. This could look something vaguely like
data Value
= IntVal !Int
| BoolVal !Bool
| Closure { environment :: [Value]
, expr :: Exp }
现在,您需要 eval :: Exp->值
以评估表达式.还有很多工作.
Now you'll want eval :: Exp -> Value
to evaluate expressions. There's lots of work left.
这篇关于制作类型:添加数据类型和不匹配类型的评估器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!