[Haskell-beginners] Using derived Show most of the time

Brent Yorgey byorgey at seas.upenn.edu
Sat Dec 11 21:31:05 CET 2010


On Sat, Dec 11, 2010 at 08:45:22AM -0800, Russ Abbott wrote:
> I have a data type for which I want to generate my own show string in a few
> cases, e.g.,
> 
> *data *T =    T1 ...
>              | T2 ...
>              | T3 ...
>              ...
> 
> 
> I'd like to do something like this,
> 
> *instance *Show T *where*
>      show T5 ... = <something special>
>      show t = showTheDerived t
> 
> 
> Is there a way to do something like that simply?

Unfortunately, there isn't quite.  There are two solutions that I can
think of, both slightly sub-optimal:

  (1) Just derive the normal Show instance for T.  Then make a newtype
  wrapper around T,
 
    newtype NiceT = NiceT T

  and give T2 a show instance like

    instance Show T2 where
      show (NiceT (T5 ...)) = <something special>
      show (NiceT t)        = show t

  that way when you want a T shown specially you can wrap it in a
  NiceT constructor.

  (2) Make a new type class

    class Pretty p where
      ppr :: p -> String

  and write an instance of it for T in terms of T's derived Show
  instance.  This solution satisfies those people who argue that Show
  should always print out valid Haskell expressions that could be,
  say, pasted into ghci (and I admit to leaning in that direction
  personally) and using a different class for human-readable,
  pretty-printed representations.  But of course the nice thing about
  Show is that it gets used automatically for values in ghci, and with
  this solution you have to explicitly wrap things in calls to ppr.

-Brent



More information about the Beginners mailing list