如何定义由其他数据类型组成的数据类型? [英] How do I define a data type consisting of other data types?
问题描述
我想定义数据类型Currency,它由其他三种数据类型组成.我有一个问题,Haskell无法将数据类型识别为货币的一部分,从而破坏了一切.
I want to define the data type Currency, which consists of three other data types. I have the problem that Haskell doesn't recognize the data types as a part of currency, which breaks everything.
我的想法是将不同的货币定义为它们自己的数据类型,然后将它们添加到货币"类型中,我尝试使用以下类型:
My idea was to define the different currencies as their own data types and then add them to the Currency type, which I tried with:
data Euro = MkEuro Integer Integer
data Dollar = MkDollar Integer Integer
data Yen = MkYen Integer
data Currency = Euro | Dollar | Yen
如果我想在任何函数中使用Currency类型,则会收到以下错误消息的变体:
If I want to use the type Currency in any function I get a variation of the following error message:
Couldn't match expected type `Currency' with actual type `Dollar'
遗憾的是,我必须使用货币"类型,并且不能为所有三种货币创建不同的功能.
Sadly I have to use the type Currency and can't create different functions for all three currencies.
推荐答案
当前,您的Currency
被构造为三个值,这些值带有 no 参数.因此,Euro
是一个值,Dollar
是一个值,Yen
是一个值,但不是MkYen 15
.
Currently your Currency
is constructed as three values, that take no parameters. So Euro
is a value, Dollar
is a value, and Yen
is a value, but not MkYen 15
.
您可以将参数添加到数据构造函数中,例如:
You can add parameters to your data constructors like:
data Currency = Euro Euro | Dollar Dollar | Yen Yen
然后,您可以使用以下命令构造Currency
:
Then you thus can construct a Currency
with:
Euro (MkEuro 14 25) :: Currency
MkEuro
将构造一个Euro
类型的对象,然后我们使用类型为Euro -> Currency
的Euro
data 构造函数构造一个Currency
.
The :: Currency
is not necessary. The MkEuro
will thus construct an object of the Euro
type, and then we use the Euro
data constructor with type Euro -> Currency
to construct a Currency
.
不幸的是,我必须使用类型
Currency
,并且不能为所有三种货币创建不同的功能.
Sadly I have to use the type
Currency
and can't create different functions for all three currencies.
您可能想制作一个Currency
typeclass ,它提供了一个界面,该界面说明货币应实现的功能,然后制作Euro
,Dollar
和Yen
该类型类的实例.
You might want to make a Currency
typeclass however, that provides an interface that says what functions a currency should implement, and then make Euro
, Dollar
, and Yen
instances of that typeclass.
这篇关于如何定义由其他数据类型组成的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!