[Haskell-cafe] How to define Show [MyType] ?

Dmitri O.Kondratiev dokondr at gmail.com
Thu Dec 4 17:27:05 EST 2008

I am trying to define instance Show[MyType] so
show (x:xs :: MyType) would return a single string where substrings
corresponding to list elements will be separated by "\n".
This would allow pretty printing of MyType list in several lines instead of
one, as default Show does for lists.

For example:

data ShipInfo = Ship {
      name :: String,
      kind :: String,
      canons :: Int
} deriving Show

s1 = Ship {name ="HMS Fly", kind = "sloop", canons=16}
s2 = Ship {name ="HMS Surprise", kind = "frigate", canons=42}

-- Yet when I try to define:
instance (Show ShipInfo) => Show [ShipInfo] where
    show (x:xs) = "<" ++ show x ++ ">" ++ show xs

-- I get this error:
    Illegal instance declaration for `Show [ShipInfo]'
        (The instance type must be of form (T a b c)
         where T is not a synonym, and a,b,c are distinct type variables)
    In the instance declaration for `Show [ShipInfo]'
Failed, modules loaded: none.

-- On the other hand this definition:
instance (Show a) => Show [a] where
    show (x:xs) = "<" ++ show x ++ ">" ++ show xs

-- Gives a different error:
    Duplicate instance declarations:
      instance (Show a) => Show [a]
        -- Defined at C:/wks/haskell-wks/ShowMatrix.hs:37:0
      instance (Show a) => Show [a] -- Defined in GHC.Show
Failed, modules loaded: none.

-- Note the last error implicitly tells us that defining Show [a] is
possible in principle!
-- In fact it already defined in GHC.Show !!!

--  How to define Show [MyType] ?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20081205/8095778c/attachment.htm

More information about the Haskell-Cafe mailing list