模板Haskell声明中的局部变量 [英] Local variables in Template Haskell declarations

查看:86
本文介绍了模板Haskell声明中的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 pozorvlak的模板哈斯克尔的宝贝步骤以试图了解它我自己,我碰到这一节:


回想一下,我们试图以编程方式产生形式的数据的声明Fred = Fred 。让我们尝试quasiquoting。由于调用TH代码的限制,我们必须将它放在它自己的模块中,所以让我们将以下内容放入Keyword.hs中,以便编译器可以找到它:



< pre $ module关键字(关键字)其中

import Language.Haskell.TH.Syntax
关键字名称= [d | data $(name)= $(name)|]

现在编译:

  Prelude> :l Keyword.hs 
[1 of 1]编译关键字(Keyword.hs,解释)

Keyword.hs:6:24:解析输入`$('


这和我一起敲响了一下,似乎和我读过的其他东西类似最近,模板Haskell包文档


对于动态绑定的事物( NameS )我们可能希望它们以一种依赖于上下文的方式,所以我们不需要名称空间。例如:

  let v = mkNameTi​​n [| data $ v = $ v |] 

对于类型构造函数和数据构造函数,使用相同的名称

几乎相同,让我们看看我能否得到这个工作:

  module例子w这里
import Language.Haskell.TH
let v = mkNameTi​​n [|数据$ v = $ v |]

给它一个旋转:

 %ghc -XTemplateHaskell -c Example.hs 

Example.hs:3:25:输入`data'的解析错误

嗯...哦,也许我需要使用 d

  let v = mkNameTi​​n [d |数据$ v = $ v |] 

现在:

  Example.hs:3:31:对输入'$ v'解析错误

所以......发生了什么事?使用显式拼接不会更改任何错误。我是否将模板Haskell文档置于上下文之外,还是仅仅是错误的?解析方案

看起来这是一个版本为GHC超过6.12,其中不能拼接类型


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?

解决方案

Looks like it's a bug with versions of GHC older than 6.12 where you can't splice in types.

这篇关于模板Haskell声明中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆