Created
November 2, 2015 23:03
-
-
Save erantapaa/a5aab1f80e51d60a7b59 to your computer and use it in GitHub Desktop.
Template Haskell examples
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, 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) | |
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
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