Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 379
rampion Avatar asked Apr 19 '11 20:04

rampion


1 Answers

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

like image 103
rampion Avatar answered Sep 29 '22 17:09

rampion