如何定义由其他数据类型组成的数据类型? [英] How do I define a data type consisting of other data types?

查看:101
本文介绍了如何定义由其他数据类型组成的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义数据类型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 -> CurrencyEuro 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 ,它提供了一个界面,该界面说明货币应实现的功能,然后制作EuroDollarYen该类型类的实例.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆