本文介绍了为什么除了Haskell中的类型构造函数外,还有一个值构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我是Haskell的新手,目前正在通过Real World Haskell。本书说类型构造函数仅用于类型签名,而值构造函数用于实际代码中。它也给出了一个声明的例子,表明两者的名称是相互独立的。为什么首先需要两个构造函数,如果其中只有一个用于实际代码?由于我们不会在实际代码中使用类型构造函数,因此类型构造函数的目的是什么? 解析方案

也许名称是有点误导。 类型构造函数表示您声明的类型的名称。它们就是这样调用的,因为它们构建的是类型,而不是值:实际上,(可能)对类型变量进行参数化,它们定义了一系列类型。它们的行为类似于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中的类型构造函数外,还有一个值构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:39