[Haskell-cafe] instance of String illegal
Stefan Holdermans
stefan at cs.uu.nl
Fri Sep 29 02:37:56 EDT 2006
Adam,
> 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
"no"
> mkFoo [False, True]
"no, yes"
> mkFoo 'h'
"h"
> mkFoo "haskell"
"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).
HTH,
Stefan
More information about the Haskell-Cafe
mailing list