schemeracketquasiquotes

Behavior of "unquote" when used as the second to last symbol in a quasiquoted proper list


I am trying to produce the list (1 unquote 2) using quasiquote. I have tried this:

`(1 unquote 2)

However, in Racket, MIT Scheme and Chez Scheme, I get a dotted list: '(1 . 2).

So I tried this:

`(1 'unquote 2)

However, I get (1 'unquote 2).

I finally got the list I wanted using this technique:

`(1 unquote 2 ,((lambda (x) x) 'unquote) 2)  ; Returns: '(1 unquote 2)

Why do I get a dotted list out of a quasiquoted proper list when unquote is the second to last element in the quasiquoted list?

Actually, it does not always produce a dotted list. For example:

`(1 unquote (list 2 3 4))  ; Returns: '(1 2 3 4)

Please explain this strange behavior of unquote when it is the second to last element in a quasiquoted list.


Solution

  • (a b c) is a shorthand for (a . (b . (c . ()))).

    So (quasiquote (1 unquote 2)) is really (quasiquote (1 . (unquote 2))) which is '(1 . 2).

    (Or if you want to fully expand it, (quasiquote (1 unquote 2)) is (quasiquote . ((1 . (unquote . (2 . ()))) . ())))

    Similarly, (quasiquote (1 unquote (list 2 3 4))) is really (quasiquote (1 . (unquote (list 2 3 4)))) = (quasiquote (1 . (2 3 4))) = '(1 2 3 4).

    By the way, an easier way to produce '(1 unquote 2) using quasiquote is:

    `(1 ,'unquote 2)