What is the use of `,` and `,@` in Racket?

188 Views Asked by At

I'm new to Racket and I was hoping to get more insights in the these two operators: , & ,@. There's very little documentation of these new operators, however, to my understanding the former (,) unquotes everything if its is followed by a list. And the latter (,@) splices the values.

For example if the following is typed in the Dr. Racket interpreter:

(define scores '(1 3 2))
(define pets '(dog cat))

and then the following query is made:

`(,scores ,@pets)

this would yield : '((1 3 2) dog cat)

It would be appreciated if I could get more details, definitions and more examples about these operators. Thanks in advance.

2

There are 2 best solutions below

0
On BEST ANSWER

A single quote followed by the written representation of a value will produce that value:

Example: '(1 x "foo") will produce a value that prints as (1 x "foo").

Suppose now that I don't want a literal symbol x in the list. I have a variable x in my program, and I want to insert the value to which x is bound.

To mark that I want the value of x rather than the symbol x, I insert a comma before x:

'(1 ,x "foo")

It won't work as-is though - I now get a value that has a literal comma as well as a symbol x. The problem is that quote does not know about the comma convention.

Backtick or backquote knows about the comma-convention, so that will give the correct result:

> `(1 ,x "foo")
(1 3 "foo")          ; if the value of x is 3

Now let's say x is the list (a b).

> `(1 ,x "foo")
(1 (a b) "foo")          ; if the value of x is (a b)

This looks as expected. But what if I wanted (1 a b "foo") as the result? We need a way so show "insert the elements of a list". That's where ,@ comes into the picture.

> `(1 ,@x "foo")
(1 a b "foo")          ; if the value of x is (a b)
0
On

They are "reader abbreviations" or "reader macros". They are introduced in the section of the Racket guide on quasiquotation. To summarize:

`e     reads as   (quasiquote e)
,e     reads as   (unquote e)
,@e    reads as   (unquote-splicing e)

Because Racket's printer uses the same abbreviations by default, it can be confusing to test this yourself. Here are a few examples that should help:

> (equal? (list 'unquote 'abc) (read (open-input-string ",abc")))
#t
> (writeln (read (open-input-string ",abc")))
(unquote abc)

A more exhaustive description of the Racket reader is in the section on The Reader in the Racket Reference. A list of reader abbreviations is in the Reading Quotes subsection.