Newbie question 'bout car/cdr

Discussion of Common Lisp
Post Reply
dio
Posts: 1
Joined: Sat Feb 26, 2011 7:48 am

Newbie question 'bout car/cdr

Post by dio » Sat Feb 26, 2011 8:01 am

Hello all! Maybe this question is very easy, but I can't find the solution.

the output of (caadr (cadr ’(a ’(b (c))))) is b
if we'll execute the second part of the expression: (cadr ’(a ’(b (c)))), the output will be ’(b (c))
but, the output of (caadr ’(b (c))) is c, not b! Why does it happen?

sorry for my bad english

ramarren
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland
Contact:

Re: Newbie question 'bout car/cdr

Post by ramarren » Sat Feb 26, 2011 8:21 am

The quote syntax is a shorthand for writing a list with the first element being the symbol QUOTE and the second element being the form following the quote.

The symbol QUOTE designates a special operator. It is treated specially by the evaluator, in that it prevents evaluation, but otherwise it is a symbol as any other. Since the first QUOTE in your example prevents evaluation the inner quotes are just expanded by the reader algorithm.

Code: Select all

’(a ’(b (c))) == (quote (a (quote (b (c)))))
Nested quotes are almost always confusing. Just don't do that. Also, Common Lisp has many other datastructures, if you are using deeply nested lists it is probably a sign you want to use classes or hashtables or something.

JamesF
Posts: 98
Joined: Thu Jul 10, 2008 7:14 pm

Re: Newbie question 'bout car/cdr

Post by JamesF » Sun Feb 27, 2011 7:15 pm

These functions are often confusing, which is why people usually tell you not to use them.
I use them myself sometimes, so I'll just suggest that you think them through very carefully.

It may help to decompose it step-by-step:
(cadr (foo))
becomes
(car (cdr foo))

So (cadr ’(a ’(b (c))))
becomes
(car (cdr '(a '(b (c)))))
-> (car '(b (c)))
-> b

I'll leave it to you to work through the second one, but it will help to point out that (cdr '(b (c))) will effectively return (list (list c)), or '((c)).


HTH,
James

Post Reply