简体   繁体   English

用泛型键入代数数据类型

[英]Typing algebraic data type with generic type

data List t = E | C t (List t)
  deriving Show

lst1 :: List Int
lst1 = C 2 E

Why is t typed to 2 in case ? 为什么将t键入2以防万一? As the first guard defines "t = E" is this reason (List t) is allowed, so "C t (List t)" can also be read "C t E" ? 由于第一个警卫定义了“ t = E”,因此是允许(List t)原因,因此“ C t(列表t)”也可以读作“ C t E”?

data NonEmptyList a = NEL a [a]
lst2 :: NonEmptyList = 2

Why can't 2 be typed to a as t is typed to 2 in above case ? 为什么不能2键入到at在上述的情况下输入到2?

In the first type: 在第一种类型中:

data List t = E | C t (List t)

t is a type parameter , it must be provided as an existing type. t类型参数 ,必须作为现有类型提供。 E is not a type, it is a data constructor , or value constructor . E不是类型,它是数据构造函数值构造函数 C is also a data constructor. C也是数据构造函数。 They have the types: 它们具有以下类型:

E :: List t
C :: t -> List t -> List t

You could construct values like 你可以构造像

> E :: List Int  -- Equivalent to []
E
> C 1 E :: List Int  -- Equivalent to [1]
C 1 E
> C 1 (C 2 E) :: List Int  -- Equivalent to [1, 2]
C 1 (C 2 E)

And so on. 等等。 You can treat E as the empty list [] and C as the list constructor : , so C 1 (C 2 (C 3 E)) is equivalent to 1 : 2 : 3 : [] which is the same as [1, 2, 3] . 您可以将E视为空列表[] ,将C视为列表构造函数: ,因此C 1 (C 2 (C 3 E))等效于1 : 2 : 3 : [][1, 2, 3]是相同的[1, 2, 3]

In the second type: 在第二种类型中:

data NonEmptyList a = NEL a [a]

You have the data constructor 你有数据构造函数

NEL :: a -> [a] -> NonEmptyList a

You can construct values like 您可以构造类似的值

> NEL 1 [] :: NonEmptyList Int  -- Equivalent to [1]
NEL 1 []
> NEL 1 [2] :: NonEmptyList Int  -- Equivalent to [1, 2]

And so on. 等等。 This type forces you to always have at least one value, so it can't be non-empty. 此类型强制您始终至少具有一个值,因此它不能为非空。

When you write lst2 :: NonEmptyList = 2 , this is a syntax error, and it's hard to guess what you meant, but the equivalent NonEmptyList Int to the lst1 :: List Int would be written as NEL 2 [] :: NonEmptyList Int . 当您编写lst2 :: NonEmptyList = 2 ,这是一个语法错误,很难猜测您的意思,但是与lst1 :: List Int等效的NonEmptyList Int lst1 :: List Int将被写为NEL 2 [] :: NonEmptyList Int

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

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