[Haskell-cafe] [Probably a dumb question] Quasiquoting

Andrew Coppin andrewcoppin at btinternet.com
Tue Mar 31 13:04:27 EDT 2009


Robert Greayer wrote:
> With some more context:
>
> foo = ($expr "1 + 2")
>
> v.
>
> bar = [$expr| 1 + 2]
>
> In the first example (assuming TH is enabled), $expr is a splice, which happens at compile time. 'expr' is some value of type Q Exp (the AST for a Haskell expression, in the quotation monad).  The application of $expr to the value "1 + 2" happens at runtime (assuming $expr splices a value of type String -> a, otherwise its a compile time error).
>
> In the second example, expr is a value of type QuasiQuoter, which contains an element quoteExpr, a function of type String -> Q Exp, which is applied at compile time to the contents of the quasiquotation (" 1 + 2"), and the result spliced in.  The value of 'foo' and 'bar' could work out to be exactly the same, depending on the implementation of expr in each instance.  But the 'work' of expr in the first instance happens when the value of foo is demanded, whereas in the second case, it happens at compile time.
>
> Of course, you could also have:
>
> foo = $(expr "1 + 2")
>
> In this case expr is a function of type String -> Q Exp, which is applied to its argument "1 + 2" at compile time.  It is very similar to the QQ example.  One advantage to qq is that you can do:
>
> foo s = [$expr|
>     int main(int argc, char** argv) {
>         printf("hello $s!\n");
>     }
>
>   |]
>
> assuming your expression parser supports anti-quotation.  Also you can in theory put qq's in patterns:
>
> foo y [$expr|printf($_)|] = [$expr|printf($y)|]
>
> although take this example with a grain of salt (I've not played with this aspect of quasiquotation).  Note also that antiquotation syntax is completely up to the QuasiQuoter (the $s, $_, could just as easily be @{s} or ***_***, or something else, depending on the implementation of expr).
>   

Definitely a dumb question. I wrote ($expr "1 + 2") instead of $(expr "1 
+ 2") - which, as you point out, is something rather different.

Is there some reason why you can't have antiquoting with normal TH?

I'm just trying to make sure I've understood QQ correctly...



More information about the Haskell-Cafe mailing list