[Haskell-beginners] Boilerplate Code
Matt Andrew
mjsaand at gmail.com
Wed Aug 4 22:07:08 EDT 2010
I had a play today and managed to figure out how to write the code I needed. If anyone is curious the resulting code is:
{-# LANGUAGE TemplateHaskell #-}
module Template where
import Language.Haskell.TH
typeChecker :: String -> Q Exp
typeChecker schemeType = do
x <- newName "x"
return $ LamE [VarP x] (CaseE (VarE x) [Match (ConP ty [WildP]) (NormalB (AppE (ConE bool) (ConE true))) [],Match WildP (NormalB (AppE (ConE bool) (ConE false))) []])
where ty = mkName schemeType
bool = mkName "Bool"
true = mkName "True"
false = mkName "False"
I then import this module into where I am defining the predicates (templates have to be defined in a seperate module), where the code becomes:
numberP :: SchemeVal -> SchemeVal
numberP = $(typeChecker "Number")
boolP :: SchemeVal -> SchemeVal
boolP = $(typeChecker "Bool")
symbolP :: SchemeVal -> SchemeVal
symbolP = $(typeChecker "Symbol")
So, as I always knew, not really worth the effort as I've written a 13 line module to save 3 lines of code, but a good learning experience =) Thanks again for the point in the right direction.
Cheers,
Matt
More information about the Beginners
mailing list