Search code examples
haskellnewtype

overload show for list


I want a newline-separated representation instead of the usual comma separated one, for may new data tyepe:

newtype SimpleRecord = SimpleRecord ([Char], [Char], Integer)
    deriving (Show)

I tried to write this istance of Show class :

instance  Show [SimpleRecord] where
        show [(SimpleRecord (n, i, c))] = show (SimpleRecord (n, i, c))++['\n']
        show (l:ls) = (show l)++['\n']++(show ls)

GHC heavily insults me.

Can someone try to explain me what can I do?


Solution

  • First, the Show class is supposed to be for producing Haskell source code, which the Read class can then read back in. It isn't supposed to be for producing human-readable, "pretty" output.

    Having just said that, almost everyone misuses it for the latter, and it can be helpful for debugging purposes.

    So, your options are:

    1. Write some function not called show which does what you want. (As per AndrewC's comment.)

    2. Use the showList method.

    If you write deriving Show, this tells the compiler to write all the Show methods for you. If you want to write them yourself, you need to take away the deriving bit first. Then you can write your instance, which is going to look something like

    instance Show SimpleRecord where
      show (SimpleRecord (x, y, z)) = ...
    
      showList rs = unlines (map show rs)
    

    As an aside, if you didn't already know this, you can write

    mapM_ print records
    

    at the GHCi prompt to print out any list of printable things with one element per line.


    As a final asside, why

    newtype SimpleRecord = SimpleRecord ([Char], [Char], Integer)
    

    rather than

    data SimpleRecord = SimpleRecord [Char] [Char] Integer