[Haskell-beginners] how to modify show for a list of certain types

Daniel Fischer daniel.is.fischer at googlemail.com
Sat Apr 2 15:51:33 CEST 2011


On Saturday 02 April 2011 15:32:07, Manfred Lotz wrote:
> Hi there,
> I have a list of say type  Record which I write to a file and
> read back from the file if required.
> 
> The list's content is a single line in the file it doesn't matter how
> many records the list contains.
> 
> I would like to modify show for type Record in a way that show does
> work like the normal show but additionally adds a newline at the end of
> the string.
> 
> I'm a bit lost how to do that. Any idea?

There's a showList function in the Show class, you can use that to define 
non-standard list displays (as it's done for [Char] = String).
You cannot then derive the Show instance, which may be a minor 
inconvenience or a major pain.
In the latter case, you could define a newtype,

newtype RecordList = RL [Record]

instance Show RecordList where
    show (RL xs) = unlines (map show xs)

and use that to display when you want things on separate lines.

Or you could modify the function used to writing the file, instead of

hPutStrLn fileHandle (show recordList)

mapM_ (hPrint fileHandle) recordList



More information about the Beginners mailing list