弃用-XDatatypeContext的替代方案? [英] Alternative for deprecated -XDatatypeContext?

查看:79
本文介绍了弃用-XDatatypeContext的替代方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  { - #LANGUAGE DatatypeContexts# - } 
类节点a其中
getContent ::(Num a)=> a

data(Node a)=>树a =叶a
|分支a(Tree a)(Tree a)

-XDatatypeContexts现已弃用。有没有可能做类似的事情?

你认为它做到了?这是弃用,因为它基本上是无用的,并被广泛认为是错误的,因为它所做的只是强制你添加额外的约束而没有提供任何类型的保证,超出你没有它的类型。



替代品,比如它,实际上确实有用,是 GADT语法。相当于你的类型:

 数据树a其中
Leaf ::(Node a)= > a - >树a
Branch ::(Node a)=> a - >树a - >树a - >树a

在这种情况下,您需要 Node Tree 值时,c>约束,但是当在 Tree 值上进行模式匹配时,您也可以自动保证存在一个 Node 实例,使得该实例在接收 Tree a 的函数类型中不需要它即可使用参数。


Let's say I want to define a tree like this:

{-# LANGUAGE DatatypeContexts #-}
class Node a where
  getContent :: (Num a) => a

data (Node a) => Tree a = Leaf a
                        | Branch a (Tree a) (Tree a)

-XDatatypeContexts is deprecated now. Is it possible to do something similar without it?

解决方案

Are you sure datatype contexts actually did what you think it did? It was deprecated because it was basically useless and widely considered a misfeature, since all it did was force you to add extra constraints without providing any guarantees about types beyond what you'd have had without it.

The replacement, such as it is, that actually does something useful, is GADT syntax. The equivalent of your type would look like this:

data Tree a where
    Leaf :: (Node a) => a -> Tree a
    Branch :: (Node a) => a -> Tree a -> Tree a -> Tree a

In this case, you need the Node constraint when creating a Tree value, but when pattern matching on a Tree value you also get an automatic guarantee that a Node instance exists, making the instance available without even needing it in the type of the function receiving Tree a as an argument.

这篇关于弃用-XDatatypeContext的替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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