car and cdr in Scheme are driving me crazy

(cdr x) = ((bc) d ( (ef) g ) )
(cdr(cdr x)) = (d ( (ef) g ) )
(cdr(cdr(cdr x))) = (( (ef) g ) )
(car(cdr(cdr(cdr x)))) = ( (ef) g )
(cdr(car(cdr(cdr(cdr x))))) = (g)
(car(cdr(car(cdr(cdr(cdr x)))))) = g

do the transforms one at a time. cdr gives you a list without the first element, car gives you the first element.

(cdr (a (bc) d ( (ef) g ) )) -> ( (bc) d ( (ef) g ) )
(cdr ( (bc) d ( (ef) g ) ))  -> ( d ( (ef) g ) )
(cdr ( d ( (ef) g ) ))       -> ( ( (ef) g ) )
(car ( ( (ef) g ) ))         -> ( (ef) g )  <- pulls the first element out, which happens to be a list itself
(cdr ( (ef) g ))             -> (g)
(car (g))                    -> 'g

this is easy/compact way to get the value of the list.

(cadr (cadddr x))

by combining repeating functions, you get elegant easy to read statement.


Try to do it step by step:

  • cdr yields the list without the first element
  • car yields the first element of a list

                                  x         is  (a (bc) d ( (ef) g ))
                             (cdr x)        is  (  (bc) d ( (ef) g ))
                        (cdr (cdr x))       is  (       d ( (ef) g ))
                   (cdr (cdr (cdr x)))      is  (         ( (ef) g ))
              (car (cdr (cdr (cdr x))))     is            ( (ef) g )
         (cdr (car (cdr (cdr (cdr x)))))    is            (      g )
    (car (cdr (car (cdr (cdr (cdr x))))))   is                   g
    

Tags:

Scheme