[英]How to define a recursive data type that refers to its definition
I want to write a data type to evaluate the expressions like this: 我想写一个数据类型来评估这样的表达式:
a
is evaluated to a
a
被评估为a
a + b * c / d -e
is evaluated to a + (b * (c / (d - e)))
a + b * c / d -e
被评估为a + (b * (c / (d - e)))
So the first argument is always a number and the second one is either a number or an expression 所以第一个参数总是一个数字,第二个参数是数字或表达式
I have tried to define a data type like this 我试图定义这样的数据类型
data Exp = Single Int
| Mult (Single Int) Exp
But it gives me this compilation error: 但它给了我这个编译错误:
Not in scope: type constructor or class ‘Single’
A data constructor of that name is in scope; did you mean DataKinds?
|
9 | | Mult (Single Integer ) Exp
|
I can define it like this: 我可以这样定义:
data Exp = Single Integer
| Mult Exp Exp
But it does not give the precise definition of the Type I want. 但它没有给出我想要的类型的精确定义。 How can I define this? 我怎么定义这个?
But it does not give the precise definition of the Type I want. 但它没有给出我想要的类型的精确定义。
Single a
is not a type. Single a
不是一个类型。 Single
is a data constructor . Single
是数据构造函数 。 So Single a
does not make much sense. 所以Single a
没有多大意义。
You can use Exp
here as first parameter, or if you want to restrict the first operand, you can use: 您可以在此处使用Exp
作为第一个参数,或者如果要限制第一个操作数,可以使用:
data Exp a = Single a | Mult a (Exp a)
Indeed, since Single a
just wraps an a
, you can use an a
as first parameter of Mult
. 实际上,由于Single a
只包含一个a
,你可以使用a
作为Mult
第一个参数。 The Mult
data constructor context, makes it clear how to interpret that a
. Mult
数据构造函数上下文,清楚地说明了如何解释a
。
If you want to allow multiplying two Exp a
s, then you can define this as: 如果要允许乘以两个Exp a
s,则可以将其定义为:
data Exp a = Single a | Mult (Exp a) (Exp a)
You can use generic abstract data types (GADTs) to make finer specifications when two expressions can be multiplied. 当两个表达式可以相乘时,您可以使用通用抽象数据类型(GADT)来制定更精细的规范。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.