[Haskell-cafe] type/class question: toString

Thomas Schilling nominolo at googlemail.com
Tue Nov 6 12:03:10 EST 2007


On Tue, 2007-11-06 at 09:18 -0500, Graham Fawcett wrote:
> Hi folks,
> 
> Is there a way to declare a 'toString' function, such that
> 
> toString x | <x is a String> = x
> toString x | <x's type is an instance of Show> = show x
> 
> Perhaps, in the type system, there's a way to declare a ToString
> class, and somehow "inherit" all instances of Show as ToString
> instances?

I think the simpler solution (for your particular problem) is to tag
strings that should be printed as-is:

newtype Literal = Literal String

instance Show Literal where show (Literal x) = x

lit :: String -> Literal
lit = Literal 

I generally try to keep the law

  read . show == id

Thus, for anything that needs to be printed in a nicer way I use
something like this:

class PPrint a where
  pretty :: a -> Doc   




More information about the Haskell-Cafe mailing list