[Haskell-beginners] Re: pretty-printing data
Christian.Maeder at dfki.de
Mon Aug 31 07:31:51 EDT 2009
Michael Mossey wrote:
> For debugging purposes I'm interested in pretty-printing data; to start
> with, lists of algebraic data types. Basically I'd like 'show' with the
> ability to put each entry of a list on a separate line, and indented.
> Note that the algebraic data might have an inner list as one of its
> elements, so this is a non-obvious formatting problem.
> I believe I can make instances of Show, can I not? Is there something
> called showList which I can use to code my own method of showing lists
> of a particular type? My understanding is that I can't make [a] an
> instance of Show; hence they provided showList.
For your own data type say "Foo" you can provide your own showList
definition, that will be used whenever you show something of type
"[Foo]". You cannot rewrite the (generic) "instance Show a => Show [a]".
instance Show Foo where
show _ = "Foo"
showList l s = unlines (map ((" " ++) . show) l) ++ s
With overlapping instances you could rewrite "instance Show [Foo]", but
you should prefer the above or start with a separate class "Pretty" and
use show as default implementation:
class Show a = Pretty a
pretty :: a -> String
pretty = show
With some ghc extension (undecidable instances?) you can get instances
for all types:
instance Show a = Pretty a
Provide a list instance:
instance Pretty a => Pretty [a] where
pretty l = ...
and you can write (overlapping) instances for other types. For your own
data types use "deriving Show" and provide a Pretty instance (if you
don't like the Show result).
More information about the Beginners