Skip to content

Instantly share code, notes, and snippets.

@shangaslammi
Created December 27, 2011 19:59
Show Gist options
  • Save shangaslammi/1524967 to your computer and use it in GitHub Desktop.
Save shangaslammi/1524967 to your computer and use it in GitHub Desktop.
Template Haskell Example
{-# 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)|]
{-# LANGUAGE TemplateHaskell #-}
import CustomShow
data MyData = MyData
{ foo :: String
, bar :: Int
}
listFields ''MyData
main = print $ MyData { foo = "bar", bar = 5 }
@aluink
Copy link

aluink commented May 24, 2013

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment