使用 TemplateHaskell 生成数据声明

Generate a data declaration with TemplateHaskell

我想知道如何根据名称列表生成一堆常量。

我从这个工作示例开始:

ConstantCreation.hs

module ConstantCreation where

import Language.Haskell.TH

createConstant :: String -> Q [Dec]
createConstant constantName = do constantType   <- newName constantName
                                 constant       <- newName constantName
                                 return [ DataD []
                                          constantType []
                                          [NormalC constant []]
                                          []                       ]

MyConstants.hs

{-# LANGUAGE TemplateHaskell #-}

module MyConstants where

import ConstantCreation

$(do constantsDeclarations <- mapM createConstant
                                       [ "MyFirstCustomConstant"  ,
                                         "MySecondCustomConstant"   ]
     return $ mconcat constantsDeclarations)

但是当我尝试添加 deriving Show.

时事情变得棘手

我首先尝试像这样更改函数 createConstant

createConstant constantName = do constantType   <- newName constantName
                                 constant       <- newName constantName
                                 return [ DataD []
                                          constantType []
                                          [NormalC constant []]
                                          [GHC.Show.Show]          ]

如果我在 GHCi 中 运行 命令 runQ [d|data MyConstant = MyConstant deriving Show|],那么它会抛出错误 Not in scope: data constructor ‘GHC.Show.Show’

所以我试着像这样定义我的函数:

createConstant constantName = [d|data $(ConT $ newName constantName) = $(NormalC (newName constantName) []) deriving Show|]

但是我遇到了以下错误:

Cannot parse data constructor in a data/newtype declaration: $(NormalC
                                                                 (newName constantName) [])

要手动定义Show实例真的很可惜,所以我想知道是怎么回事。

感谢任何建议或解释。

您可以使用 ''Show 获取名称在范围内的 Type

{-# LANGUAGE TemplateHaskell #-}

module Constant where

import Language.Haskell.TH

createConstant constantName = do
    tname <- newName constantName
    cname <- newName constantName
    return [DataD [] tname [] [NormalC cname []] [''Show]]