[Haskell-cafe] type/class question: toString

Bayley, Alistair Alistair_Bayley at invescoperpetual.co.uk
Tue Nov 6 10:30:23 EST 2007

> From: haskell-cafe-bounces at haskell.org 
> [mailto:haskell-cafe-bounces at haskell.org] On Behalf Of Graham Fawcett
> 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'm assuming you're not fond of the way the print function handles

With GHC you can do this:

> {-# OPTIONS -fallow-overlapping-instances #-}
> {-# OPTIONS -fallow-undecidable-instances #-}
> class Show a => MyShow a where show_ :: a -> String
> instance MyShow String where show_ s = s
> instance (Show a) => MyShow a where show_ s = show s

Confidentiality Note: The information contained in this message,
and any attachments, may contain confidential and/or privileged
material. It is intended solely for the person(s) or entity to
which it is addressed. Any review, retransmission, dissemination,
or taking of any action in reliance upon this information by
persons or entities other than the intended recipient(s) is
prohibited. If you received this in error, please contact the
sender and delete the material from any computer.

More information about the Haskell-Cafe mailing list