user6023611
user6023611

Reputation:

haskell, deriving Show in class and in all instances

That's signature of my class:

 class (Ord a) => Test a where

I would like to be able show element a from all instances of class Test.
So far I have used deriving Show mechanism only in connection to data type.

Could you help me ?

Upvotes: 0

Views: 284

Answers (1)

daniel gratzer
daniel gratzer

Reputation: 53901

You can require that to be part of the Test type class you need to also belong to Show with

  class (Ord a, Show a) => Test a where

and then you can write a function like

printTest :: Test a => a -> IO ()
printTest a = putStrLn (show a) -- equivalent to print a

because GHC will infer that if Test a holds then Show a must as well.

But it almost seems like this isn't what you're asking for, if you want to specify a new Show instance for every type which belongs to Test then sadly you're out of luck. You could imagine writing something like

 instance Test a => Show a where
   ...

but this isn't going to work properly, in particular it will "overlap" with all other instances in a most unpleasant way and trying to fix this is just going to leave you with 2 dozens tabs into the GHC extensions manual and an elevated blood pressure. Some libraries provide a function

 defaultShow :: Test a => a -> String

if they define a type class where you would like to do this which simplifies the processes of defining such a Show instance but it's no more concise than just using deriving truthfully.

Upvotes: 1

Related Questions