Skip to content

Instantly share code, notes, and snippets.

@nh2
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nh2/161108a6acc456d4b545 to your computer and use it in GitHub Desktop.
Save nh2/161108a6acc456d4b545 to your computer and use it in GitHub Desktop.
Haskell sorcery with Generics and Typeable for showing the structure of any value
import GHC.Generics
import Data.Typeable
deriving instance Show (f p) => Show (M1 i c f p)
deriving instance (Show (f p), Show (g p)) => Show ((f :*:g) p)
deriving instance (Show (f p), Show (g p)) => Show ((f :+:g) p)
deriving instance (Show c) => Show (K1 i c p)
deriving instance Show (V1 p)
deriving instance Show (U1 p)
deriving instance Show D
deriving instance Show C
deriving instance Show S
class ShowIO a where
showIO :: a -> IO String
instance forall a . (Generic a, Show a, Show (Rep a ())) => ShowIO (IORef a) where
showIO ref = readIORef ref >>= \x -> return $ "IORef " ++ show (from x :: Rep a ())
-- Alternatively, don't descend into IORefs, then we can do it purely.
-- With this, `show (x :: IORef Mytype)` just gives `"IORef Mytype".
instance forall a . (Typeable a) => Show (IORef a) where
show x = "IORef " ++ show (typeOf x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment