在Haskell中定义新类型

发布于 2025-01-28 13:36:16 字数 263 浏览 1 评论 0原文

我是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 call
x = Vector [2.4,2.5,2.7] for example?

I'm using ghci, if that makes any difference

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你げ笑在眉眼 2025-02-04 13:36:16

是 - 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 function TypeConstructor :: Type1 -> Type2 -> ... -> TypeN -> TypeName, and there is special syntactic sugar for lists so that what would normally have to be something like List Float to instead be [Float].

So data Vector = Vector [Float] creates a function Vector :: [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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文