Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GHCI stack overflow on `instance Show MyType`

Why do I get stack overflow trying to do this in GHCI (version 7.6.2)? How can I derive a typeclass instance during a GHCI session or why is this not possible?

*Main> data T = T Int
*Main> let t = T 42
*Main> instance Show T
*Main> t
*** Exception: stack overflow

I know I can use deriving Show at the type declaration, but this trick would be useful for inspecting types loaded from files.

like image 846
Dmytro Sirenko Avatar asked Dec 26 '22 02:12

Dmytro Sirenko


1 Answers

You need to implement at least one of show or showsPrec for the instance to work. In the class, there are default implementations of show using showsPrec (via shows), and of showsPrec using show:

showsPrec _ x s = show x ++ s
show x          = shows x ""

and

shows           =  showsPrec 0

so

instance Show T

creates a looping instance. Calling show calls showsPrec, which calls show, which ...

With the StandaloneDeriving language extension, you can

ghci> :set -XStandaloneDeriving
ghci> deriving instance Show T

derive the instance at the prompt.

like image 88
Daniel Fischer Avatar answered Jan 13 '23 17:01

Daniel Fischer