Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of CAR, CDR, CADAR, etc

Tags:

command

scheme

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.

like image 596
Targeter 10 Avatar asked Oct 28 '12 19:10

Targeter 10


2 Answers

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.
like image 181
didierc Avatar answered Nov 16 '22 01:11

didierc


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.

like image 41
Olaf Dietsche Avatar answered Nov 16 '22 02:11

Olaf Dietsche