[Haskell-cafe] Class instances on class constraints

Dušan Kolář kolar at fit.vutbr.cz
Wed Jul 28 06:58:53 EDT 2010


  Hello all,

   For school purposes, I would like to define something like this:

module SetOverList(
          SetFromList
        , SetOL(..)
        ) where


type SetFromList a = [a]


addEq :: Eq a => a -> SetFromList a -> SetFromList a
addEq v [] = [v]
addEq v l@(x:xs) = if x==v then l else x : addEq v xs

addOrd :: Ord a => a -> SetFromList a -> SetFromList a
addOrd v [] = [v]
addOrd v l@(x:xs) =
   case compare x v of
     GT -> v : l
     EQ -> l
     LT -> x : addOrd v xs


class SetOL a where
   addElem :: a -> SetFromList a -> SetFromList a


instance (Eq a) => SetOL a where
   addElem = addEq


instance (Ord a) => SetOL a where
   addElem = addOrd


which does not work, of course (Flexible or Undecidable instances won't 
help). The aim is to have addElem function that works differently 
according to situation whether a type, which is base of the list/set, is 
a member of class Eq or Ord. Could you point me or hint me how to get as 
close as possible to the required solution? Maybe I'm not able to see an 
obvious way...

Thanks,

Dušan




More information about the Haskell-Cafe mailing list