StationaryTraveller
StationaryTraveller

Reputation: 1469

Indetifying nested quotes and unquote it in scheme

I'm trying to create a special folding function.

I have a problem regarding quotes, Especially them nested ones. It seems like they are sometimes interpeted as the start of a list, And sometimes as a quote.

Say i've got the next code:

'(x '(a b c))

Then:

(car '(x '(a b c)))

Will return: x. While:

(cadr '(x '(a b c)))

Will return: '(a b c). What does this mean? Is this a list? if so why does:

(caadr '(x '(a b c)))

Returns: quote. What is the meanning of this quote? Is there any way to indentify those kind of lists? And if so, Is there any way to unquote them?

Upvotes: 0

Views: 580

Answers (1)

Óscar López
Óscar López

Reputation: 236004

When we're evaluating a quoted expression, remember that this expression: 'x is just shorthand for this: (quote x). For example:

'(x '(a b c))

Is equivalent to:

(quote (x (quote (a b c))))

Now this expression will also return a quoted expression, which happens to start with yet another quoted expression:

(cadr (quote (x (quote (a b c)))))
                ---------------
=> ''(a b c)

This is more apparent in the next example, where we end up retrieving the 'quote symbol itself:

(caadr (quote (x (quote (a b c)))))
                  -----
=> 'quote

For the last part of the question: if you want to interpret the innermost list as a list and not as a quoted expression, then don't quote it at all:

(cadr '(x (a b c)))
=> '(a b c)

Of course, we could also leave the second quote and eval the innermost list, but that's a hassle and potentially evil:

(define-namespace-anchor a)
(define ns (namespace-anchor->namespace a))

(eval (cadr '(x '(a b c))) ns)
=> '(a b c)

Or we could use quasiquoting and unquoting:

(cadr `(x ,'(a b c)))
=> '(a b c)

Upvotes: 3

Related Questions