[英]Haskell types and value constructor
Reading through a book I came across Haskell Bool Type which is通读一本书,我遇到了 Haskell Bool Type 这是
data Bool = True | False
As I understand in this case True and False are values and the expression of below type is valid据我了解,在这种情况下 True 和 False 是值,以下类型的表达式是有效的
c = True
Later on, when I wanted to create a new type I forgot to name the Value constructor and created the following type.后来,当我想创建一个新类型时,我忘记命名 Value 构造函数并创建了以下类型。
data Cartesian2D = Double Double
In this case, Haskell (GHCI) did not complain.在这种情况下,Haskell (GHCI) 没有抱怨。
But when I tried to construct a value like但是当我试图构建一个像
x = 1.0 2.0
and和
x = Double Double
in both cases, Haskell returned an error.在这两种情况下,Haskell 都返回了错误。
In this case,在这种情况下,
Is the type Cartesian2D valid? Cartesian2D 类型是否有效?
if the type is not valid, why did Haskell not complain when I was constructing the type?如果类型无效,为什么在构造类型时 Haskell 没有抱怨? but only informed me while constructing a value of the type.
但只在构造类型的值时通知我。
Data constructors like True
and type constructors like Bool
exist in separate namespaces.像
True
这样的数据构造函数和像Bool
这样的类型构造函数存在于不同的命名空间中。 True
is an example of a nullary constructor, taking no arguments. True
是一个空构造函数的示例,不采用 arguments。 As such, the definition因此,定义
data Cartesian2D = Double Double
defines a type constructor named Cartesian2D
and a unary data constructor named Double
.定义了一个名为
Cartesian2D
的类型构造函数和一个名为Double
的一元数据构造函数。 Non-nullary data constructors behave much like functions, taking arguments to return a value of their associated type.非空数据构造函数的行为很像函数,使用 arguments 返回其关联类型的值。 Here,
Double
behaves like a function of type Double -> Cartesian2D
(again, note that the type constructor Double
and the type constructor Double
are distinct ).在这里,
Double
的行为类似于Double -> Cartesian2D
类型的 function(再次注意,类型构造函数Double
和类型构造函数Double
是不同的)。
x = Double 1.0
y = Double 2.0
To create a "real" Cartesian point type that stores two doubles, try something like要创建存储两个双精度的“真实”笛卡尔点类型,请尝试类似
data Cartesian2D = Point Double Double
which defines a data constructor Point
that takes two values of type Double
to create a value of type Cartesian2D
.它定义了一个数据构造函数
Point
,它接受两个Double
类型的值来创建一个Cartesian2D
类型的值。
If you are at all bothered by the fact that nullary data constructors are somehow "special" in not behaving like functions (ie, you don't have to call True
, it just is a value), you can think of nullary constructors as being shorthand for unary constructors that take a dummy argument of type ()
:如果您对 null 数据构造函数在某种程度上“特殊”而不像函数的行为这一事实感到困扰(即,您不必调用
True
,它只是一个值),您可以将 null 构造函数视为采用()
类型的虚拟参数的一元构造函数的简写:
True :: Bool
is short for简称
True () :: () -> Bool
which would always have to be used as True ()
otherwise.否则,它总是必须用作
True ()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.