[Haskell-cafe] Template Haskell Splicing

adam vogt vogt.adam at gmail.com
Sat Dec 15 20:53:21 CET 2012


On Sat, Dec 15, 2012 at 9:24 AM, satvik chauhan <mystic.satvik at gmail.com> wrote:
> Yeah, that is the problem. I have a function inside which I need to generate
> some declarations using TH. I can not generate these at the top level as
> these generations depend on the function's parameters which are local to the
> function.
>
> Something like
>
> f p1 p2= ...
>   where
> -- this has to be generated by TH
>      g_1 = p1
>      g_2 = p2
>      g_3 = p1 `xor` p2
>
> something like the above. In the above I have shown only 2 parameters but in
> my case it is much more. I am able to get the above splice as toplevel
> declaration but I am still unsuccessful in getting it inside the where.
> I can always make `g` a function and take parameters of `f` as arguments in
> the top level splice but that will defeat the purpose of optimization
> here(which I am trying to do), as that would result in a function call every
> time I use `g` instead of above variables.

Hi Satvik

Perhaps you could put the variables whose evaluations are shared in a 'let':

> f p1 p2 = $(mkG [| g_1 |])
> mkG body = liftM2 LetE [d| g_1 = $(dyn "p1") |] body

The above example won't work exactly because the two occurences of g_1
are different names. But you could replace the [d|  |] with something
that has a [Dec] with variables defined in such a way that they can be
captured.

On a somewhat unrelated note, GHC is less able to infer types for
expression splices than for top level bindings. The issue had
something to do with needing to typecheck all the $( x :: ExpQ ) as a
group, even if the values could be defined in separate modules. It
might not be an issue in your case, but one possible way around it is
have the definition of 'f p1 p2 = ... ' done by template haskell. But
then there is the issue that top level splices are run in order, so


-- this doesn't work:
{-# LANGUAGE TemplateHaskell #-}
[d| y = x |]
[d| x = 1 |]


-- This does work:
{-# LANGUAGE TemplateHaskell #-}
[d| x = 1 |]
[d| y = x |]



More information about the Haskell-Cafe mailing list