代码之家  ›  专栏  ›  技术社区  ›  Michael Thomas

类型族实例上的类型类约束

  •  15
  • Michael Thomas  · 技术社区  · 10 年前

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

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

    data family Channel c :: *

    非常感谢,

    迈克尔

    1 回复  |  直到 10 年前
        1
  •  16
  •   chi    10 年前

    这就是你要找的吗?

    {-# 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