类型对数据声明的限制 [英] Typeclass constraints on data declarations

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

问题描述

显然,在数据声明中放置一个类型类型约束是一个坏主意 [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天全站免登陆