Class name

Say we have a heterogeneous list

data Nil
data Cons a b

I can write such code for any type A

class AList a
instance AList Nil
instance (A x, AList xs) => AList (Cons x xs)

Now, is there a way to generalize this code so that it is parametric in A?

Let's say how the syntax did it

class List (class A) a
instance List (class A) Nil
instance (A x, List (class A) xs) => List (class A) (Cons x xs)
+4
source share
1 answer

Not sure I understand the motivation, but yes, you can express it with the GHC extension ConstraintKinds:

{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeclasses #-}
{-# LANGUAGE UndecidableInstances #-}

import GHC.Exts (Constraint)

class List (c :: * -> Constraint) a

data Nil
data Cons a b

instance List c Nil
instance (c x, List c xs) => List c (Cons x xs)
+3
source

All Articles