在类型族实例上键入类约束

时间:2014-08-09 13:39:11

标签: haskell types typeclass type-families

是否可以指定类型族的所有实例必须满足的类型类约束?

例如,给定以下声明,我如何确保所有实例也是Eq的实例:

data family Channel c :: *

非常感谢,

迈克尔

1 个答案:

答案 0 :(得分:13)

这是你在找什么?

{-# LANGUAGE FlexibleContexts, TypeFamilies, FlexibleInstances #-}

-- Data family inside a class so that we can add an extra Eq constraint
class Eq (Channel c) => MyClass c where
    data Channel c :: *

-- A simple toy instance
instance MyClass Int where
    data Channel Int = CI Int deriving Eq

-- A more complex instance with separate Eq instance
instance MyClass Char where
    data Channel Char = CC Char

instance Eq (Channel Char) where
   (CC x) == (CC y) = x == y