How to explain this behaviour of ghc ?

Hi, when loaded in ghci (version 6.8.2) the following code snippet data Test = A Int instance Show Test main = print (A 1) leads to: *Main> main *** Exception: stack overflow How to explain that ? Thanks, Sylvain

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 message. 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 Tillmann

-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Tillmann Rendel wrote:
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 message.
Actually, "show = undefined" isn't assumed. The problem is that the default definitions for show and showsPrec are: showsPrec _ x s = show x ++ s show x = showsPrec 0 x "" This allows you to define either one of showsPrec or show, and have a reasonable default definition for the other one. However, if you leave off the definition of _both_ of them, what you get is an infinite recursion (hence the stack overflow). - -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer. GNU Maintainer: wget, screen, teseq http://micah.cowan.name/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFI79Bu7M8hyUobTrERAnTLAJ4i3jfeS8QQQBSXqBNVW0Ph77GYKQCeKzXn BPo7VBKIn/7t4Z8FoU+FbYc= =7ovS -----END PGP SIGNATURE-----
participants (3)
-
Micah Cowan
-
sylvain
-
Tillmann Rendel