[Haskell-cafe] type class question

Stefan Holdermans stefan at cs.uu.nl
Tue May 22 01:06:23 EDT 2007


Tim,

> If I have a type class for conversion to a type X:
>
>     class XType a where
>         toX   :: a -> X

[...]

>     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
> variables)
>     In the instance declaration for `XType String'

In addition to Derek's pointer, you could also consider extending the  
class definition:

   class XType a where
     toX     :: a   -> X
     listToX :: [a] -> X
     listToX =  ... -- some default definition for listToX

Of course, it depends on your type X whether a suitable default  
definition for listToX can be given. Assuming that it can, you can  
now, as before, have

   instance XType Int where toX  = ...
   instance XType Double where toX  = ...
   instance XType Tuple where toX  = ...

but also

   instance XType Char where
     toX c     = ...  -- your toX implementation for Char
     listToX s = ...  -- your toX implementation for String

This 'trick' is used in the standard libraries to accommodate a Show  
instance for String, for instance.

Cheers,

   Stefan


More information about the Haskell-Cafe mailing list