Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you derive Show for type defined in someone else's library?

I'm using a Haskell library for OAuth and the author didn't derive Show for a type I am using and would like to be able to print out for debugging. I would like to derive Show for it. Is there any way to do this from outside the library, apart from building up a function copies all the record fields into a record type that does derive Show?

The type in question is Token from Network.OAuth.Consumer:

http://hackage.haskell.org/packages/archive/hoauth/0.3.5/doc/html/src/Network-OAuth-Consumer.html#Token

like image 265
dan Avatar asked Oct 10 '12 15:10

dan


1 Answers

You can use a GHC extension called StandaloneDeriving.

With this extension, you can write expressions like:

deriving instance Show Token

To use this, put

{-# LANGUAGE StandaloneDeriving #-}

at the top of your file.

The syntax for a standalone derivation is essentially exactly the same as the syntax for an instance statement, except preceded by deriving and without a where clause. This means you can write more specific instance like:

deriving instance Show a => Foo (Maybe a)

You also have to explicitly give the context needed for your instance. You would have to write a standalone instance like this:

deriving instance Show a => Show (Foo a)

That is, you have to explicitly note the Show a context needed.

This shouldn't come up in your case, but it's something to keep in mind.

like image 133
Tikhon Jelvis Avatar answered Oct 18 '22 21:10

Tikhon Jelvis