[Haskell-cafe] instance of String illegal

Stefan Holdermans stefan at cs.uu.nl
Fri Sep 29 02:37:56 EDT 2006


> class Foo a where
>     mkFoo :: a -> String
> instance Foo String where
>     mkFoo x = x

In addition to making use of language extensions or wrapper types,  
you could go with the following workaround in just plain Haskell 98:

   import List

   class MkFoo a where
     mkFoo     :: a -> String

     mkFooList :: [a] -> String
     mkFooList =  concat . intersperse ", " . map mkFoo

   instance MkFoo Char where
     mkFoo     = (: [])
     mkFooList = concatMap mkFoo

   instance (MkFoo a) => MkFoo [a] where
     mkFoo = mkFooList

For instance:

   > mkFoo False

   > mkFoo [False, True]
   "no, yes"

   > mkFoo 'h'

   > mkFoo "haskell"

The same approach is taken for implementing Show in the standard  
libraries. Note that it requires you to fix the type constructors  
that are to be treated in a special manner ([] in the above example).



More information about the Haskell-Cafe mailing list