Targeter 10
Targeter 10

Reputation: 213

Explanation of CAR, CDR, CADAR, etc

Can someone please give me a basic explanation of what the variations of car and cdr do in Scheme?

If I am correct, car will return the first item in the list. cdr will return a list excluding the first element.

I'm confused on the other variations of these, more specifically things like cadar, caddr, cddr, etc.

Say I have this as a random example:

define X '(a b (c d e))

(car X)
(cdr X)
(cadr X)
(cadar X)

(car X) would produce a, (cdr X) would produce (b (c d e)), cadr would produce b. But I don't know how to infer any other variation of car/cdr like cadar.

Upvotes: 21

Views: 22433

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74048

The easiest way is to enter it into a scheme interpreter:

(car X)   -> a
(cdr X)   -> (b (c d e))
(cadr X)  -> (car (cdr X))       -> (car '(b (c d e))) -> b
(cadar X) -> (car (cdr (car X))) -> (car (cdr 'a))     -> error

When you have more than one a or d, as you can see from the cadr example, you can read it backwards. First take the cdr (d) of the argument, then take the car (a) from the result, and so on until you get to the first one.

Upvotes: 12

didierc
didierc

Reputation: 14730

You can infer the meaning of these functions by parsing their name:

between the first letter ('c') and the last ('r'), a 'a' means "the car of" and a 'd' means "the cdr of".

So:

  • cadr is "the car of the cdr",
  • cddr is the cdr of the cdr,
  • cadar is the "car of the cdr of the car" (thus the parameter has to be a list of list),
  • etc.

Upvotes: 37

Related Questions