[Haskell-beginners] Re: Showing control characters

Brent Yorgey byorgey at seas.upenn.edu
Tue Nov 9 22:56:33 EST 2010


On Tue, Nov 09, 2010 at 11:44:42AM -0800, Russ Abbott wrote:
> I wasn't at a computer with Haskell when I wrote the earlier message.
>  Here's how it seems to work.
> 
> File:
> 
> *data *MyType = MyType
> 
> *instance *Show MyType *where*
>     show MyType = "a\nb"

There's nothing too magical going on here. Remember that show just
converts a value to a String.  How that String is then displayed
depends on what you do with it, not with the definition of show.

> 
> 
> 
> Load the above file. Then:
> 
> > MyType        -- This does what I want it to do after all.
> a
> b

ghci essentially does "putStrLn . show" on the results of expressions
typed at the prompt.  So the call to show results in the string
consisting of an a, a newline, and a b, and putStrLn prints that
string to the screen (with the newline interpreted appropriately).

> 
> > show MyType
> "a\nb"

'show MyType' is an expression of type String.  Doing putStrLn . show
on it causes show to be called on the string, which converts it to a
form surrounded by quotes and with control characters escaped.  The
resulting string is then printed to the screen.

> 
> > putStrLn (show MyType)
> a
> b

This is the same as the first example, since IO actions entered at the
ghci prompt are simply run.

> 
> > print MyType
> a
> b

This is also the same, since print = putStrLn . show.


More information about the Beginners mailing list