Template Haskell 声明中的局部变量
我正在阅读 pozorvlak 在 Template Haskell 上的婴儿步骤帖子,试图自己理解它,并且我遇到了这个部分:
回想一下,我们试图以编程方式生成
data Fred = Fred
形式的声明。让我们尝试一下准引用。由于调用 TH 代码的限制,我们必须将其放在自己的模块中,因此我们将以下内容放入 Keyword.hs 中,以便编译器可以找到它:模块关键字(keyword) 其中 导入 Language.Haskell.TH.Syntax 关键字名称 = [d|数据 $(名称) = $(名称) |]
现在编译:
前奏> :l 关键字.hs [1 of 1] 编译关键字(Keyword.hs,解释) Keyword.hs:6:24:输入“$(”时解析错误
这给我敲响了警钟,看起来很相似我最近读过的其他内容, Template Haskell 包文档:
对于动态绑定的事物(
NameS
),我们可能希望它们以上下文相关的方式进行,因此我们再次不需要名称空间。例如:让 v = mkName "T" in [|数据 $v = $v |]
这里我们对类型构造函数和数据构造函数使用相同的
名称
好吧,这几乎是一样的,让我们看看我是否可以让它工作:
module Example where
import Language.Haskell.TH
let v = mkName "T" in [| data $v = $v |]
试一试:
% ghc -XTemplateHaskell -c Example.hs
Example.hs:3:25: parse error on input `data'
嗯...哦,也许我需要使用 d
进行声明引用?
let v = mkName "T" in [d| data $v = $v |]
现在:
Example.hs:3:31: parse error on input `$v'
那么……发生了什么事?使用显式拼接不会改变任何一个错误。我是否断章取义地使用了 Template Haskell 文档,或者它只是错误的?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来这是 6.12 之前的 GHC 版本的一个错误,其中 你无法拼接类型。该错误已在 GHC 7.10.1 版本中修复
Looks like it's a bug with versions of GHC older than 6.12 where you can't splice in types. This bug was fixed in GHC version 7.10.1