Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type class constraint on type family instances

Is it possible to specify a type class constraint that must be satisfied by all instances of a type family?

For example, given the following declaration, how would I ensure that all instances are also instances of Eq:

data family Channel c :: *

Many thanks,

Michael

like image 458
Michael Thomas Avatar asked Aug 09 '14 13:08

Michael Thomas


1 Answers

Is this what you are looking for?

{-# 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
like image 76
chi Avatar answered Oct 20 '22 22:10

chi