Skip to content

Instantly share code, notes, and snippets.

@JohnLato
Created October 29, 2013 06: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 JohnLato/7209766 to your computer and use it in GitHub Desktop.
Save JohnLato/7209766 to your computer and use it in GitHub Desktop.
simple collection of meta information via Data/Generics
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
module Foo where
import GHC.Generics
import Data.Data
newtype FooT = FooD Int deriving (Generic, Data, Typeable)
someFoo :: FooT
someFoo = FooD 7
{- We can use generics to get the constructor name from someFoo,
- as well as internal constructor information:
*Foo >let (_,types) = runWriter $ gmapM (\d -> tell [typeOf d] >> return d)
someFoo
*Foo>> :t types
types :: [TypeRep]
*Foo> types
[Int]
-}
{- We can use getConName on the rep generated from someFoo as well
-
*Foo GHC.Generics> getConName $ from someFoo
"FooD"
-}
class GConName a where
getConName :: a -> String
instance (GConName (b c)) => GConName (M1 D a b c) where
getConName (M1 x) = getConName x
instance Constructor a => GConName (M1 C a b c) where
getConName = conName
-- a full Generic class would typically have more instances.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment