Skip to content

Instantly share code, notes, and snippets.

@daimatz
Created November 4, 2012 15:01
Show Gist options
  • Save daimatz/4012200 to your computer and use it in GitHub Desktop.
Save daimatz/4012200 to your computer and use it in GitHub Desktop.
Data Convert Function using Template Haskell
{-# LANGUAGE TemplateHaskell #-}
import Language.Haskell.TH
import Control.Applicative ((<$>))
data Hoge = Hoge1 | Hoge2 | Hoge3 deriving (Eq, Show)
data Fuga = Fuga1 | Fuga2 deriving (Eq, Show)
-- runQ [| \t -> case t of "hoge1" -> Hoge1; "hoge2" -> Hoge2; "hoge3" -> Hoge3; _ -> error "Hoge" |]
convertHogeTH :: ExpQ
convertHogeTH = do
t_0 <- newName "t"
return $ LamE [VarP t_0]
(CaseE (VarE t_0)
[ Match (LitP (StringL "hoge1")) (NormalB (ConE 'Hoge1)) []
, Match (LitP (StringL "hoge2")) (NormalB (ConE 'Hoge2)) []
, Match (LitP (StringL "hoge3")) (NormalB (ConE 'Hoge3)) []
, Match WildP (NormalB (AppE (VarE 'error) (LitE (StringL "Hoge")))) []
]
)
mkConvertFunc' :: Name -> [(String, Name)] -> ExpQ
mkConvertFunc' d lst = do
t_0 <- newName "t"
return $ LamE [VarP t_0]
(CaseE (VarE t_0)
$ (map (\(s, t) -> Match (LitP (StringL s)) (NormalB (ConE t)) []) lst)
++ [Match WildP (NormalB (AppE (VarE 'error) (LitE (StringL $ show d)))) []])
$(do
info <- reify ''Hoge
runIO $ print info
return [])
$(do
ctrs <- (\(TyConI (DataD [] _ [] x [])) -> map (\(NormalC name []) -> name) x)
<$> reify ''Hoge
runIO $ print $ ctrs
return [])
mkConvertFunc :: Name -> [String] -> ExpQ
mkConvertFunc d strs = do
ctrs <- (\(TyConI (DataD [] _ [] x [])) -> map (\(NormalC name []) -> name) x)
<$> reify d
v <- newName "x"
return $ LamE [VarP v]
(CaseE (VarE v)
$ (map (\(s,t) -> Match (LitP (StringL s)) (NormalB (ConE t)) []) $ zip strs ctrs)
++ [Match WildP (NormalB (AppE (VarE 'error) (LitE (StringL $ show d)))) []])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment