GHCI Stack Overflow on `instance Show MyType`

Why am I getting a stack overflow trying to do this in GHCI (version 7.6.2)? How can I get an instance of typeclass 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 that I can use the deriving Show in a type declaration, but this trick would be useful for checking the types loaded from files.

+4
source share
1 answer

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

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

and

 shows = showsPrec 0 

So

 instance Show T 

creates an instance of the loop. A call to show calls showsPrec , which calls show , which ...

With the StandaloneDeriving language extension you can

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

print a copy at the invitation.

+10
source

Source: https://habr.com/ru/post/1484624/


All Articles