[Haskell-cafe] Possible to automatically determine typeclass membership?

jeff p mutjida at gmail.com
Mon Mar 31 01:30:50 EDT 2008


Hello,

> Is it possible in Haskell + GHC extensions to use reflection
>  techniques to determine typeclass membership?  I'm thinking of things
>  like the following:
>
I think the short answer is not in general; i.e. I don't think there is any
way to access the members of an arbitrary typeclass (but I'd love to be
proved wrong).

However, you could always explicitly list the members of a typeclass you are
interested in (this is similar to your Idea 2):

{-# OPTIONS_GHC -fglasgow-exts -fallow-undecidable-instances
-fallow-overlapping-instances #-}

class InEq a b | a -> b where inEq :: a -> Bool
instance TypeCast b HFalse => InEq a b where inEq _ = False
instance InEq Int HTrue where inEq _ = True
instance InEq a b => InEq [a] b where inEq _ = inEq (undefined :: a)

data HTrue
data HFalse

class TypeCast   a b   | a -> b, b-> a   where typeCast   :: a -> b
class TypeCast'  t a b | t a -> b, t b -> a where typeCast'  :: t -> a -> b
class TypeCast'' t a b | t a -> b, t b -> a where typeCast'' :: t -> a -> b
instance TypeCast'  () a b => TypeCast a b where typeCast x = typeCast' () x
instance TypeCast'' t a b => TypeCast' t a b where typeCast' = typeCast''
instance TypeCast'' () a a where typeCast'' _ x  = x

You can also do an arguably nicer, more flexible version of the previous by
recreating some of the typeclass machinery yourself; Oleg has several
examples of this such as: //okmij.org/ftp/Haskell/poly2.txt

-Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20080331/5ac0f4b2/attachment.htm


More information about the Haskell-Cafe mailing list