Local variables in Template Haskell declarations

I'm reading through pozorvlak's baby steps post on Template Haskell in an attempt to understand it myself, and I came across this section:

Recall that we were trying to programmatically produce declarations of the form data Fred = Fred . Let's try it with quasiquoting. Because of the restrictions on calling TH code, we'll have to put it in its own module, so let's put the following in Keyword.hs so the compiler can find it:

module Keyword (keyword) where

import Language.Haskell.TH.Syntax
keyword name = [d| data $(name) = $(name) |]

Now compile:

Prelude> :l Keyword.hs
[1 of 1] Compiling Keyword          ( Keyword.hs, interpreted )

Keyword.hs:6:24: parse error on input `$('

This rung a bell with me, and seemed similar to something else I had read recently, the Template Haskell package documentation:

For dynamically bound thing ( NameS ) we probably want them to in a context-dependent way, so again we don't want the name space. For example:

let v = mkName "T" in [| data $v = $v |]

Here we use the same Name for both type constructor and data constructor

Well, that's almost the same, let's see if I can get that to work:

 module Example where
 import Language.Haskell.TH
 let v = mkName "T" in [| data $v = $v |]

Give it a whirl:

 % ghc -XTemplateHaskell -c Example.hs

 Example.hs:3:25: parse error on input `data'

Hmm... Oh, maybe I need to use the d for declaration quoting?

 let v = mkName "T" in [d| data $v = $v |]

and now:

 Example.hs:3:31: parse error on input `$v'

So.... what's going on? Using explicit splices doesn't change either error. Am I taking the Template Haskell documentation out of context, or is it just wrong?


看起来这是一个GHC版本高于6.12的版本,无法在类型中拼接。

链接地址: http://www.djcxy.com/p/52080.html

上一篇: C ++代理类

下一篇: 模板Haskell声明中的局部变量