简体   繁体   English

Haskell代数数据类型

[英]Haskell Algebraic Data Types

I have the following for an HTML font tag: 对于HTML字体标签,我具有以下内容:

data Color = HexColor Int | RGBColor Int Int Int | ColorString String deriving Show
data FontAttribute = Size Int | Face String | FontColor Color deriving Show
data Font = Font [FontAttribute] deriving Show

I construct one like so: 我这样构造一个:

Font [Size 23,Face "Arial",Color (RGBColor 240 23 43)]

My concern is that the FontColor data/value constructor which has type FontAttribute requires a Color type as an argument. 我担心的是类型为FontAttribute的FontColor数据/值构造函数需要Color类型作为参数。 This means that Color is a generic type attribute for any kind of tag, and a specific tag has a specific subset of attributes (in this case Font has FontAttribute, which can be Size, Face or FontColor). 这意味着Color是任何类型标记的通用类型属性,并且特定标记具有特定属性子集(在这种情况下,Font具有FontAttribute,可以是Size,Face或FontColor)。 Is there a clearer way to express this, or is my implementation sound? 有没有更清晰的表达方式,或者我的实现听起来不错?

Color is just a type, not an attribute. 颜色只是一种类型,而不是属性。 There is nothing in the type system to indicate that Color has any special relationship with FontAttribute. 类型系统中没有任何东西可以指示Color与FontAttribute有特殊关系。 All that happens when you define the FontAttribute data type is that it creates a constructor called FontColor which is an ordinary function with the following type signature: 定义FontAttribute数据类型时,所发生的一切就是创建一个名为FontColor的构造函数,该构造函数是具有以下类型签名的普通函数:

FontColor :: Color -> FontAttribute

So if you declared some new type called Link: 因此,如果您声明了一种称为Link的新类型:

data LinkAttrubute = LinkColor Color | ...

Then Color could be stored in a LinkAttribute, too. 然后,颜色也可以存储在LinkAttribute中。 A constructor does not imply an exclusive relationship with only that data type. 构造函数并不意味着仅与该数据类型存在排他关系。 All your FontAttribute data type says is that it MIGHT contain just a Color. 您所有的FontAttribute数据类型都说明它可能只包含一个Color。

Haskell has no built-in concept of attributes because it has no built-in concept of objects. Haskell没有内置的属性概念,因为它没有内置的对象概念。 HOWEVER, you can model attributes using the Lens type from the data-lens (or fclabels) package. 但是,您可以使用data-lens(或fclabels)包中的Lens类型为属性建模。 I would link you the packages, but I'm on my phone and it is difficult. 我会链接您的软件包,但是我在打电话,很难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM