1
名前のリストに基づいて定数の束を生成する方法を知りました。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
を変えてみました:私はGHCiの中でコマンド
runQ [d|data MyConstant = MyConstant deriving Show|]
を実行すると示唆したよう
createConstant constantName = do constantType <- newName constantName
constant <- newName constantName
return [ DataD []
constantType []
[NormalC constant []]
[GHC.Show.Show] ]
、それは
Not in scope: data constructor ‘GHC.Show.Show’
は、だから私はのように私の関数を定義し、DOしようとしたエラーをスローしますこの:
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インスタンスを手動で定義する必要があるのは本当にうんざりです。だから私は何がうまくいかないのだろうかと思います。
アドバイスや説明をありがとう。
「eleveConstr」とは何ですか? – Sibi
'GHC.Show.Show'とは何ですか?あなたはおそらくTHスプライスの名前を表現したいと思うでしょう - '' 'Show'や' 'showCon < - mkName" Show "' – user2407038
@Sibiコードを修正しました。私は例を自己文書化するために元のコードを変更しましたが、忘れました。 – Echologie