DatatypeContexts Deprecated in Latest GHC: Why?

我与影子孤独终老i 提交于 2019-11-27 03:02:38
C. A. McCann

It's deprecated because it was a misfeature, and didn't actually have any useful functionality! All it did was force a bunch of extra constraints in other locations. In particular, when pattern matching on such a type, you'd be forced to add a constraint, rather than (as one might initially hope) get access to a context, based on the knowledge that one must have been available to construct the value in the first place.

The "replacement", which actually works the other way and tracks the known contexts for you, is to use GADT-style declarations instead:

data MyType a where
    ConstructorOne :: Ord a => a -> MyType a
    ConstructorTwo :: Ord a => a -> a -> MyType a

GADTs in general are more flexible in many other ways as well, but for this particular case what happens is that creating a value needs the Ord constraint, which is then carried along with the value, and pattern matching on the constructor pulls it back out. So you don't even need the context on the functions using it, because you know that by virtue of expecting something of type MyType a, you'll get an Ord a constraint with it.

In general, you still need to add the Ord a constraint to any function which uses your MyType type, and as such isn't as useful as it may seem. For more information about why they were removed, see http://hackage.haskell.org/trac/haskell-prime/wiki/NoDatatypeContexts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!