[Haskell-beginners] How to explain this behaviour of ghc ?

Tillmann Rendel rendel at daimi.au.dk
Fri Oct 10 17:46:42 EDT 2008

Hi Sylvain,

sylvain wrote:
> the following code snippet
> data Test = A Int
> instance Show Test
> main = print (A 1)
> leads to:
> *Main> main
> *** Exception: stack overflow

Since "instance Show Test" does not specify how method "show" should be
implemented for datatype Test, "show = undefined" is assumed. Now, print calls
show to create a string represention of (A 1), which produces the error

Interestingly, undefined gives a better error message, when called directly:

  Prelude> undefined
  *** Exception: Prelude.undefined

I don't know why the behaviour of undefined differs from the behaviour of
unbound methods.

If you want to correct the above program, you could either bind show to
something, as in

  instance Show Test where
    show (A n) = "(A " ++ show n ++ ")"

or you could use ask the compiler to derive an instance for you, as in

  data Test = Show Int
    deriving Show


More information about the Beginners mailing list