Haskell: Algebraic data types whose type variables must be an instance of a class

I am trying to define an algebraic type:

data MyType t = MyType t

And make it an instance of Show:

instance Show (MyType t) where
  show (MyType x) = "MyType: " ++ (show x)

The GHC complains because it cannot deduce that the type 't' in 'Show (MyType t)' is actually an instance of Show, which is needed for (show x).

I have no idea where and how to declare 't' as an instance of Show?

+3
source share
3 answers

Add a type constraint to the type t:

instance Show t => Show (MyType t) where
  show (MyType x) = "MyType: " ++ (show x)
+18
source

You can also simply:

data MyType t = MyType t
    deriving Show

if you want to have a regular display format.

+15
source

- GADT:

data MyType t  where 
   MyType :: Show a => a -> MyType a
+2

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


All Articles