[Haskell-cafe] Best way to build strings?

Lemmih lemmih at gmail.com
Wed Jul 20 13:00:22 EDT 2005


On 7/20/05, Andy Gimblett <A.M.Gimblett at swansea.ac.uk> 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 ++ ")"

How about leaving the Show instance automatically derived and defining
this instead:

showProcess :: Process -> ShowS
showProcess Stop = showString "Stop"
showProcess (Prefix l p) = showBody (showString l) (showProcess p)
showProcess (External p q) = showBody (showProcess p) (showProcess q)

showBody :: ShowS -> ShowS -> ShowS
showBody a b = showParen True (a . showString " [] " . b)

> but to me the extensive use of ++ is not particularly readable.
> 
> I'm very fond of Python's interpolation approach, where we'd have
> something like the following for the External case:
> 
>     def __str__(self):
>         return "(%s [] %s)" % (self.p, self.q)
> 
> which to me seems clearer, or at least easier to work out roughly what
> the string's going to look like.  (The %s does an implicit "convert to
> string", btw).
> 
> Is there a facility like this in Haskell?  Or something else I should
> be using, other than lots of ++ ?

There's Text.Printf:

Prelude Text.Printf> printf "(%s [] %s)" "hello" "world" :: String
"(hello [] world)"


-- 
Friendly,
  Lemmih


More information about the Haskell-Cafe mailing list