[Haskell-cafe] type class question

Tim Docker timd at macquarie.com.au
Mon May 21 20:02:29 EDT 2007

I think this must almost be a FAQ, or at least a PAQ (Previously AQ)...
If I have a type class for conversion to a type X:
    class XType a where
        toX   :: a -> X
I can define instances for 
    instance XType Int where toX  = ...
    instance XType Double where toX  = ...
    instance XType Tuple where toX  = ...
but not for Strings, given that they are a synonym for [Char]. Hence:
    instance XType String where toX  = ...
results in:
    Illegal instance declaration for `XType String'
        (The instance type must be of form (T a b c)
         where T is not a synonym, and a,b,c are distinct type
    In the instance declaration for `XType String'
Is there some type class cleverness that can make this work in haskell
98? I can create a new wrapper type for strings:

    newtype StringWrap = StringWrap String

and write an instance for that, but then I'll have to litter my code
with calls to this constructor.

I'm aware of the approach taken by class Show in the prelude, which
adds a extra method to the class:
    class XType a where
        toX     :: a -> X
        listToX :: [a] -> X
but I believe this says that whenever we can convert a to an X we can
convert [a] to an X, whereas I only want [Char] to be acceptable.
Thanks for any pointers.

More information about the Haskell-Cafe mailing list