[ ^ to index   |   <-- previous   |   next --> ]

Obtaining pieces of lists

Merely constructing lists is not very interesting. We would like to extract the pieces of a list. For this, we use the functions car and cdr. These are horrible names, but Scheme uses them for historical reasons. car returns the value referenced by first part of a cons cell; cdr returns the value referenced by the second part.

   (define p '(1 2 3))  ; Binds p to the list '(1 2 3)
   (car p)              ; => 1
   (cdr p)              ; => '(2 3)
   (car (cdr p))        ; => 2

   (define p2 (cdr (cdr p))) ; Binds p2 to the list containing 3
                             ; Note that p and p2 share the same data.

Exercises

Draw a diagram of the resulting memory and bindings.

   (define q (cons (cons "hi"
                         (cons "bye" ()))
                   (cons (cons "bonjour" "au revoir")
                        '(4 5 6))))



   (define r (cdr (car q)))




   (define s (cdr (cdr (cdr q))))




   (define t (cons (cdr q) (car q)))




   (define u (cdr r))




   (define v (list (cons 1 2)))




   (define w (list 1 2 (cdr (cdr t)) '(cdr (cdr t))))






[ ^ to index   |   <-- previous   |   next --> ]

cse341-webmaster@cs.washington.edu
Last modified: Wed Jan 9 22:39:12 PST 2002