[英]Haskell expression data type
I want to have the following data type in Haskell : 我想在Haskell中使用以下数据类型:
data Exp = Add Exp Exp
| Var String
| Let (Var String) Exp Exp
| Int Int
However, using (Var String) like that is not allowed. 但是,不允许使用这样的(Var String)。 I could use Exp instead of (Var String), but I don't want an Int to be allowed there, so how can I solve this? 我可以使用Exp代替(Var String),但是我不希望在其中使用Int,那么如何解决这个问题?
You could define a newtype wrapper Var
or just use String
. 您可以定义新的包装器Var
或仅使用String
。 First the newtype wrapper example: 首先是newtype包装器示例:
newtype Var = V String
-- ^ "Var" here is a type declaration. "V" is declaring a data constructor.
data Exp = Add Exp Exp
| Var Var -- The first "Var" here is declaring a data constructor. The second is referring to the type.
| Let Var Exp Exp -- "Var" here is referring to the type
| Int Int
Or just with strings: 或仅使用字符串:
data Exp = Add Exp Exp
| Var String
| Let String Exp Exp
| Int Int
EDIT: The point my comments were trying to make is probably unclear. 编辑:我的评论试图提出的观点可能不清楚。 In your use of Var, such as Let (Var String) Exp Exp
, you tried to use a constructor named Var
(and it's field, String
) in a location that requires a type . 在使用Var时,例如Let (Var String) Exp Exp
,您尝试在需要type的位置中使用名为Var
的构造函数(及其字段String
)。 Each data constructor can be used to build a value of the type ( Exp in this case) and can not be further distinguished by the type system. 每个数据构造函数都可用于构建类型的值 (在这种情况下为Exp ),并且不能由类型系统进一步区分。 In lieu of an additional data declaration you can't distinguish between a value of type Exp that is a Var
from one that is an Add
, Let
, or Int
. 代替其他数据声明,您无法区分类型为Exp的Var
值和类型Add
, Let
或Int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.