gpt4 book ai didi

haskell - 使用TemplateHaskell生成数据声明

转载 作者:行者123 更新时间:2023-12-01 15:58:10 24 4
gpt4 key购买 nike

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

我从这个工作示例开始:
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]]

关于haskell - 使用TemplateHaskell生成数据声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40438679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com