0

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?

StationaryTraveller
  • 1,449
  • 2
  • 19
  • 31

1 Answers1

3

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)
Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386