[Haskell-cafe] Best way to build strings?

Bernard Pope bjpop at cs.mu.OZ.AU
Thu Jul 21 02:55:15 EDT 2005


On Wed, 2005-07-20 at 17:06 +0100, Andy Gimblett wrote:
> A small stylistic question: what's the "best" way to build strings
> containing other values?  For example, I have:
> 
> data Process = Stop |
>                Prefix String Process |
>                External Process Process
> 
> instance Show Process where
>     show Stop = "Stop"
>     show (Prefix l p) = "(" ++ l ++ "->" ++ show p ++ ")"
>     show (External p q) = "(" ++ show p ++ " [] " ++ show q ++ ")"
> 
> but to me the extensive use of ++ is not particularly readable.

It is also inefficient because append has complexity proportional to the
length of its left argument. That's why the Prelude defines:

   type ShowS = String -> String

and functions like showsPrec, shows, showChar

> Is there a facility like this in Haskell?  Or something else I should
> be using, other than lots of ++ ?

It looks to me like you are doing some kind of pretty printing - that is
you are not printing the term using Haskell syntax. 

My preference is to only use Show where it is derived from the data
declaration, and use a hand-written pretty printer for other tasks,
for example Text.PrettyPrint

Cheers,
Bernie.



More information about the Haskell-Cafe mailing list