在Haskell中定义新类型
我是Haskell的新手,我想知道是否可以定义由其他类型列表定义的新类型。例如,我认为一个字符串定义为字符列表,因此我可以将向量定义为力值列表(在这种情况下为浮点值)吗?
如果是这样,我该如何声明和使用?
data vector = vector [float]
这足以定义新类型和构造函数?我可以打电话吗 x = vector [2.4,2.5,2.7]
?
我正在使用GHCI,如果有什么不同
I am pretty new to Haskell, and I was wondering if one can define new types that are defined by lists of other types. For example, I assume a string is defined as a list of characters, so can I define a vector as a list of force values (in this case floating point values)?
If so, how can I declare and use this?
data Vector = Vector [Float]
Is this enough to define the new type and the constructor for it? Can I simply callx = Vector [2.4,2.5,2.7]
for example?
I'm using ghci, if that makes any difference
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是 -
data typeName = typeconstructor type1 type2 ... typen
只是创建函数typeconstructor :: type1-> type2-> ... - >键入 - > typeName
,列表有特殊的句法糖,因此通常必须是list float
be[float]
之类的东西。因此,
data vector = vector [float]
创建函数vector :: [float] - >向量
(请注意,功能和结果类型是共享名称的不同事物)。vector
函数称为类型构造函数,类型构造函数是唯一可以以其名称具有初始大写字母的函数。Yes -
data TypeName = TypeConstructor Type1 Type2 ... TypeN
just creates a functionTypeConstructor :: Type1 -> Type2 -> ... -> TypeN -> TypeName
, and there is special syntactic sugar for lists so that what would normally have to be something likeList Float
to instead be[Float]
.So
data Vector = Vector [Float]
creates a functionVector :: [Float] -> Vector
(note that the function and the result type are different things that happen to share a name).The
Vector
function is called a type constructor, and type constructors are the only functions that can have initial capital letters in their name.