Skip to content

Instantly share code, notes, and snippets.

@erantapaa
Created November 2, 2015 23:03
Show Gist options
  • Save erantapaa/a5aab1f80e51d60a7b59 to your computer and use it in GitHub Desktop.
Save erantapaa/a5aab1f80e51d60a7b59 to your computer and use it in GitHub Desktop.
Template Haskell examples
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-}
module Foo where
import MyTH
foo x = x + 1
$(describe "dfoo" 'foo) -- defines the function "dfoo"
$(describe "dInt" ''Int)
$(describe "dBool" ''Bool)
$(describe "dplus" '(+))
$(describe "dnum" ''Num)
module MyTH where
import Language.Haskell.TH
describe :: String -> Name -> Q [Dec]
describe fname name = do
i <- reify name
let what =
case i of
ClassI _ _ -> "class with visible instances"
ClassOpI _ _ _ _ -> "class method"
TyConI _ -> "plain type constructor"
FamilyI _ _ -> "type or data family"
DataConI _ _ _ _ -> "data constructor"
VarI _ _ _ _ -> "value variable"
TyVarI _ _ -> "type variable"
let val = nameBase name ++ " is a " ++ what
clause = Clause [] (NormalB $ LitE $ StringL val) []
return $ [ FunD (mkName fname) [clause] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment