2016-11-05 5 views
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インスタンスを手動で定義する必要があるのは本当にうんざりです。だから私は何がうまくいかないのだろうかと思います。

アドバイスや説明をありがとう。

+0

「eleveConstr」とは何ですか? – Sibi

+0

'GHC.Show.Show'とは何ですか?あなたはおそらくTHスプライスの名前を表現したいと思うでしょう - '' 'Show'や' 'showCon < - mkName" Show "' – user2407038

+0

@Sibiコードを修正しました。私は例を自己文書化するために元のコードを変更しましたが、忘れました。 – Echologie

答えて

1

''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]] 
関連する問題