Created
October 29, 2013 06:01
-
-
Save JohnLato/7209766 to your computer and use it in GitHub Desktop.
simple collection of meta information via Data/Generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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