在所有类型族实例上输入约束 [英] Type constraints on all type family instances

查看:149
本文介绍了在所有类型族实例上输入约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想如果没有Template Haskell,我想要的是不可能的,但我仍然会问。



我有一个类似 Data的接口。设置 Data.IntSet

  type family Elem s :: * 
class SetLike s where
insert :: Elem s - > s - > s
会员:: Elem s - > s - > Bool
...

类型实例Elem(Set a)= a
实例Ord a => SetLike(Set a)其中
...

我有一个类型族选择最佳设置实现:

 类型系列EfficientSet elem :: * 
类型实例EfficientSet Int = IntSet
类型实例EfficientSet String = Set String - 或另一个实现

有没有办法保证 EfficientSet 实例将总是 SetLike ,并且 Elem(EfficientSet a)是如果没有这个保证,所有的函数签名都是这样的:
$





  type LocationSet = EfficientSet Location 
f ::(SetLike LocationSet,Elem LocationSet〜Location)=> ...

每次写入 SetLike LocationSet 在某种程度上是可以忍受的,但是 Elem LocationSet〜Location 使得代码理解变得更加困难,就像我一样。

解决方案

使用GHC 7.4的约束类型,您可以使用类似于

 类型EfficientSetLike a =(SetLike (EfficientSet a),Elem(EfficientSet a)〜a)

GHC早期版本中的约束

  class(SetLike(EfficientSet a),Elem(EfficientSet a)〜a)=> ; EfficientSet类似于
实例(SetLike(EfficientSet a),Elem(EfficientSet a)〜a)=> EfficientSetLike a

但是,新样式类型声明更好。



我不确定你在找什么,但听起来你只是想更容易编写/理解约束签名,在这种情况下这将工作。


I suppose what I want is impossible without Template Haskell but I'll ask anyway.

I have an interface for types like Data.Set and Data.IntSet:

type family Elem s :: *
class SetLike s where
  insert :: Elem s -> s -> s
  member :: Elem s -> s -> Bool
  ...

type instance Elem (Set a) = a
instance Ord a => SetLike (Set a) where
  ...

And I have a type family which chooses optimal set implementation:

type family EfficientSet elem :: *
type instance EfficientSet Int = IntSet
type instance EfficientSet String = Set String -- or another implementation

Is there a way to guarantee that EfficientSet instances will be always SetLike and that Elem (EfficientSet a) is a ?

Without this guarantee all function signatures will be like this:

type LocationSet = EfficientSet Location
f :: (SetLike LocationSet, Elem LocationSet ~ Location) => ...

To write each time SetLike LocationSet is somewhat tolerable, but Elem LocationSet ~ Location makes code understanding only harder, as for me.

解决方案

Using GHC 7.4's constraint kinds you could have something like

type EfficientSetLike a = (SetLike (EfficientSet a),Elem (EfficientSet a) ~ a)

You can (with appropriate extensions) get constraints like this in earlier versions of GHC

class (SetLike (EfficientSet a),Elem (EfficientSet a) ~ a) => EfficientSetLike a 
instance (SetLike (EfficientSet a),Elem (EfficientSet a) ~ a) => EfficientSetLike a 

But, the new style type declaration is much nicer.

I'm not exactly sure what you are looking for, but it sounds like you just want easier to write/understand constraint signatures, in which case this will work.

这篇关于在所有类型族实例上输入约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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