也许名称是有点误导。 类型构造函数表示您声明的类型的名称。它们就是这样调用的,因为它们构建的是类型,而不是值:实际上,(可能)对类型变量进行参数化,它们定义了一系列类型。它们的行为类似于C ++的模板和Java的泛型。在数据中MyType ab = Constr ab
,MyType是一个类型构造函数,它有两种类型 a
和 b
来构建一个新类型(MyType ab)
。
A 值构造函数是您在其他(面向对象)语言中称为构造函数的唯一部分,因为您需要它来构建该类型的值。因此,在前面的示例中,如果您将值构造函数 Constr :: a - > b - > MyType ab
,您可以创建一个值 Constrabc'd':: MyType [Char] Char
。
I'm a newcomer to Haskell and am currently going through Real World Haskell. The book says the type constructor is used only in the type signature while the value constructor is used in actual code. It also gives an example of a declaration to show that the names for both are independent of each other. Why are two constructors needed in the first place, if only one of them is used in actual code? Since we would not use the type constructor in actual code, what purpose does the type constructor serve?
Maybe the names are a little bit misleading. A type constructor represents the name of the type you're declaring. They're called like that because they build types, not values: indeed, being (possibly) parameterized on type variables they define a family of types. They act something like C++'s templates and Java's generics. In data MyType a b = Constr a b
, MyType is a type constructor that takes two types a
and b
to build a new type (MyType a b)
.
A value constructor is the only part you would call a "constructor" in other (object oriented) languages, because you need it in order to build values for that type. So, in the previous example, if you take the value constructor Constr :: a -> b -> MyType a b
, you may build a value Constr "abc" 'd' :: MyType [Char] Char
.
这篇关于为什么除了Haskell中的类型构造函数外,还有一个值构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!