Created
December 27, 2011 19:59
-
-
Save shangaslammi/1524967 to your computer and use it in GitHub Desktop.
Template Haskell Example
This file contains 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 TemplateHaskell, FlexibleInstances #-} | |
module CustomShow where | |
import Language.Haskell.TH | |
import Data.List (intercalate) | |
emptyShow :: Name -> Q [Dec] | |
emptyShow name = [d|instance Show $(conT name) where show _ = ""|] | |
listFields :: Name -> Q [Dec] | |
listFields name = do | |
TyConI (DataD _ _ _ [RecC _ fields] _) <- reify name | |
let names = map (\(name,_,_) -> name) fields | |
showField :: Name -> Q Exp | |
showField name = [|\x -> s ++ " = " ++ show ($(global name) x)|] where | |
s = nameBase name | |
showFields :: Q Exp | |
showFields = listE $ map showField names | |
[d|instance Show $(conT name) where | |
show x = intercalate ", " (map ($ x) $showFields)|] |
This file contains 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 TemplateHaskell #-} | |
import CustomShow | |
data MyData = MyData | |
{ foo :: String | |
, bar :: Int | |
} | |
listFields ''MyData | |
main = print $ MyData { foo = "bar", bar = 5 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is causing GHC to crash on me.
http://hpaste.org/88499
http://hpaste.org/88498
http://hpaste.org/88500
The Glorious Glasgow Haskell Compilation System, version 7.4.2
cabal-install version 1.16.0.2
using version 1.16.0.3 of the Cabal library