假设我有这样的数据类型:
data Color = Red | Blue | Green
如何使用templatehaskell生成这样的函数?
myShow Red = ...
myShow Blue = ...
myShow Green = ...
即。我正在寻找基于模式匹配的函数的多个定义。
答案 0 :(得分:3)
{-# LANGUAGE TemplateHaskell #-}
module Test where
import Language.Haskell.TH
data Color = Red | Blue | Green
myShow' :: Q [Dec]
myShow' = return [FunD (mkName "myShow") [mkClause 'Red, mkClause 'Blue, mkClause 'Green]]
where mkClause n = Clause [ConP n []] (NormalB $ LitE $ StringL $ nameBase n) []