[Haskell-cafe] TH instance code.
Michael Snoyman
michael at snoyman.com
Tue Jun 22 12:14:48 EDT 2010
On Tue, Jun 22, 2010 at 6:24 PM, Andy Stewart <lazycat.manatee at gmail.com>wrote:
> Hi all,
>
> I have below duplicate code, but i don't know how to use TH instance code.
>
> ------------------------------> duplicate code start
> <------------------------------
> instance Variable PageType where
> toVariant = toVariant . show
> fromVariant x = fmap (\v -> read v :: PageType) $ fromVariant x
>
> instance Variable Int where
> toVariant = toVariant . show
> fromVariant x = fmap (\v -> read v :: Int) $ fromVariant x
>
> instance Variable (Maybe Char) where
> toVariant = toVariant . show
> fromVariant x = fmap (\v -> read v :: Maybe Char) $ fromVariant x
>
> instance Variable (Maybe Int) where
> toVariant = toVariant . show
> fromVariant x = fmap (\v -> read v :: Maybe Int) $ fromVariant x
>
> instance Variable ProcessID where
> toVariant = toVariant . show
> fromVariant x = fmap (\v -> read v :: ProcessID) $ fromVariant x
>
> instance Variable GWindowId where
> toVariant = toVariant . show
> fromVariant x = fmap (\v -> read v :: GWindowId) $ fromVariant x
> ------------------------------> duplicate code end
> <------------------------------
>
> Any TH expert help?
>
> Thanks,
>
> -- Andy
>
>
mkInstance :: Name -> Q Dec
mkInstance n = do
tv <- [|toVariant . show|]
fv <- [|fmap read . fromVariant|]
return $ InstanceD [] (ConT ''Variable `AppT` ConT n)
[ FunD (mkName "toVariant") [Clause [] [NormalB tv] []]
, FunD (mkName "fromVariant") [Clause [] [NormalB fv] []]
]
mkInstances = mapM mkInstance
mkInstances [''PageType, ''Int, ..]
Haven't tried it, but it should be pretty close.
Michael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20100622/2cfcff18/attachment.html
More information about the Haskell-Cafe
mailing list