A typical restriction of various kinds

I do general class types for lists in Haskell.

class HasEmpty a where empty :: a isEmpty :: a -> Bool class HasEmpty (la) => List l where cons :: a -> la -> la uncons :: la -> (a, la) 

To give you an idea of ​​how this works, here are some examples for [] :

 instance HasEmpty [a] where empty = [] isEmpty [] = True isEmpty _ = False instance List [] where cons = (:) uncons (x:xs) = (x,xs) 

However, this causes an error:

 Not in scope: type variable 'a' 

This is caused by the HasEmpty (la) constraint. I am not desperate for this particular example, but I am interested in the concept as a whole. HasEmpty is the class for view types * , and List is the class for view types * -> * . Is it possible for me to make a typeclass type restriction of a different type than the class it restricts?

+4
source share
2 answers

In any case, you can always express the basic logic either using multiparameter types (as is done in ListLike ):

 {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} class HasEmpty a where empty :: a isEmpty :: a -> Bool class HasEmpty (la) => List la where cons :: a -> la -> la uncons :: la -> (a, la) instance HasEmpty [a] where empty = [] isEmpty [] = True isEmpty _ = False instance List [] a where cons = (:) uncons (x:xs) = (x,xs) 

Or more elegantly using type families:

 {-# LANGUAGE TypeFamilies #-} class HasEmpty a where empty :: a isEmpty :: a -> Bool class HasEmpty a => List a where type Elem a :: * cons :: Elem a -> a -> a uncons :: a -> (Elem a, a) instance HasEmpty [a] where empty = [] isEmpty [] = True isEmpty _ = False instance List [a] where type Elem [a] = a cons = (:) uncons (x:xs) = (x,xs) 
+3
source

Of course you can. For instance. this will work fine for the same two classes:

 class HasEmpty (l ()) => List l where cons :: a -> la -> la uncons :: la -> (a, la) 

or (where List1 :: (* -> *) -> * -> * )

 class HasEmpty1 (la) => List1 la where cons :: a -> la -> la uncons :: la -> (a, la) 

What you cannot do is add new variables to the constraints.

+2
source

All Articles