数据声明的类型类约束 [英] Typeclass constraints on data declarations

查看:37
本文介绍了数据声明的类型类约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然在数据声明上设置类型类约束是个坏主意 [src][src].>

我个人没有遇到过在我创建的数据类型中限制类型的愿望,但我不清楚为什么语言设计者认为允许这是一个坏主意".这是为什么?

解决方案

我个人没有遇到过在我创建的数据类型中限制类型的愿望,但我不清楚为什么语言设计者认为允许这是一个坏主意".这是为什么?

因为它具有误导性,并且与实际有用的东西完全相反.

特别是,它实际上并没有以您可能期望的方式限制数据类型中的类型.它所做的是在数据构造函数本身上设置了一个类约束,这意味着在构造一个值时你需要满足实例......但仅此而已.

因此,例如,您不能简单地定义带有 Ord 约束的二叉搜索树,然后知道任何树都有可排序的元素;查找和插入函数本身仍然需要一个 Ord 约束.您要阻止的只是构建一个包含"某些无序类型值的空树.就模式匹配而言,对包含的类型完全没有限制.

另一方面,在 Haskell 上工作的人并不认为明智的版本(人们倾向于假设提供的数据类型上下文)根本不是一个坏主意!事实上,数据类型的类约束 用 GADT 语法声明(广义代数数据类型,在 GHC 中使用 GADTs 语言编译指示启用)以明显的方式工作——你需要一个约束来构造 值,并且有问题的实例也存储在 GADT 中,因此您不需要约束来处理值,并且 GADT 构造函数上的模式匹配允许您使用它捕获的实例.

Apparently it's a bad idea to put a typeclass constraint on a data declaration [src], [src].

I haven't personally come across a desire to constrain the types within data types I've created, but it's not obvious to me why the language designers "decided it was a bad idea to allow". Why is that?

解决方案

I haven't personally come across a desire to constrain the types within data types I've created, but it's not obvious to me why the language designers "decided it was a bad idea to allow". Why is that?

Because it was misleading and worked completely backwards from what would actually be useful.

In particular, it didn't actually constrain the types within the data type in the way you're probably expecting. What it did do was put a class constraint on the data constructor itself, which meant that you needed to satisfy the instance when constructing a value... but that was all.

So, for instance, you couldn't simply define a binary search tree with an Ord constraint and then know that any tree has sortable elements; the lookup and insert functions would still need an Ord constraint themselves. All you'd prevent would be constructing an empty tree that "contains" values of some non-ordered type. As far as pattern matching was concerned, there was no constraint on the contained type at all.

On the other hand, the people working on Haskell didn't think that the sensible version (that people tended to assume data type contexts provided) was a bad idea at all! In fact, class constraints on a data type declared with GADT syntax (generalized algebraic data types, enabled in GHC with the GADTs language pragma) do work in the obvious way--you need a constraint to construct the value, and the instance in question also gets stored in the GADT, so that you don't need a constraint to work with values, and pattern matching on the GADT constructor lets you use the instance it captured.

这篇关于数据声明的类型类约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆