Behavour of nested quotes in Scheme and Racket
Asked Answered
D

1

7

While writing a function in Racket I accidently put two single quotes in front of a symbol instead of one. i.e. I accidently wrote ''a and discovered some behaviour of nested quotes that seems strange. I'm using DrRacket and tested this with both the Racket lang and the R5RS lang.

(write (pair? (quote (quote a))))

prints: #t .

(write (car (quote (quote a))))

prints: quote

But

(write (quote (quote a)))

and

(write '(quote a)))

Both print: 'a

Can someone tell me why in Scheme (and Racket) the function pair? interprets (quote (quote a))) as a pair of two elements quote and a , but the function write prints out 'a instead of (quote a) .

Day answered 2/11, 2011 at 16:55 Comment(0)
L
8

Putting a quote mark (') around a term and wrapping a quote form around it are identical. That is, they read to the same term.

So all of the following expressions are identical in Scheme:

''a
'(quote a)
(quote 'a)
(quote (quote a))

The quote form means "interpret what comes next as a datum---even if it contains another quote". The sub-term is parenthesized, so it's a list; the inner quote is just a symbol.

In some cases, the printer uses reader-abbreviations like the quote mark (') in its output. I'm a little surprised that you got write to do it, though; for me, it always writes as (quote a).

Leasehold answered 2/11, 2011 at 17:20 Comment(4)
I used DrRacket with both #lang r5rs and #lang racket and executed (write '(quote a)) and (write ''a) in both the definitions window and the interactions window and in all cases they printed 'a .Day
@HarrySpier, aha, probably has to do with DrRacket's pretty printing. If you write it to another port, like a string port (see open-output-string, etc), it produces (quote a).Leasehold
Thanks Ryan. Just after I asked the question I found in the Racket Guide 2.4.1 Quoting pairs and symbols with quote. The ' abbreviation works in output as well as input. "The REPL’s printer recognizes the symbol 'quote as the first element of a two-element list when printing output, in which case it uses ’ to print the output."Day
By chance in the Racket guide I found a special case where ''a doesn't mean '(quota a) . If you look at: Racket Guide 15.1.3 Namespaces and Modules it has the code snippet for the DrRacket interactive window of: The module->namespace function takes a quoted module path and produces a namespace for evaluating expressions and definitions as if they appeared in the module body: > (module m racket/base (define x 11)) > (require 'm) > (define ns (module->namespace ''m)) > (eval 'x ns) The inner ' indicates its a interactively declared module path and the second ' makes it a quoted form.Day

© 2022 - 2024 — McMap. All rights reserved.