Next: Construction of Lists, Previous: Lists, Up: Lists
This section describes the simple operations that are available for constructing and manipulating arbitrary graphs constructed from pairs.
Returns
#t
if object is a pair; otherwise returns#f
.(pair? '(a . b)) => #t (pair? '(a b c)) => #t (pair? '()) => #f (pair? '#(a b)) => #f
Returns a newly allocated pair whose car is obj1 and whose cdr is obj2. The pair is guaranteed to be different (in the sense of
eqv?
) from every previously existing object.(cons 'a '()) => (a) (cons '(a) '(b c d)) => ((a) b c d) (cons "a" '(b c)) => ("a" b c) (cons 'a 3) => (a . 3) (cons '(a b) 'c) => ((a b) . c)
(SRFI 1) Returns a newly allocated pair whose car is obj2 and whose cdr is obj1.
(xcons '(b c) 'a) => (a b c)
Returns the contents of the car field of pair. Note that it is an error to take the
car
of the empty list.(car '(a b c)) => a (car '((a) b c d)) => (a) (car '(1 . 2)) => 1 (car '()) error--> Illegal datum
Returns the contents of the cdr field of pair. Note that it is an error to take the
cdr
of the empty list.(cdr '((a) b c d)) => (b c d) (cdr '(1 . 2)) => 2 (cdr '()) error--> Illegal datum
(SRFI 1) The fundamental pair deconstructor:
(lambda (p) (values (car p) (cdr p)))(receive (a b) (car+cdr (cons 1 2)) (write-line a) (write-line b)) -| 1 -| 2
Stores object in the car field of pair. The value returned by
set-car!
is unspecified.(define (f) (list 'not-a-constant-list)) (define (g) '(constant-list)) (set-car! (f) 3) => unspecified (set-car! (g) 3) error--> Illegal datum
Stores object in the cdr field of pair. The value returned by
set-cdr!
is unspecified.
These procedures are compositions of
car
andcdr
; for example,caddr
could be defined by(define caddr (lambda (x) (car (cdr (cdr x)))))
This procedure is a generalization of
car
andcdr
. Path encodes a particular sequence ofcar
andcdr
operations, whichgeneral-car-cdr
executes on object. Path is an exact non-negative integer that encodes the operations in a bitwise fashion: a zero bit represents acdr
operation, and a one bit represents acar
. The bits are executed LSB to MSB, and the most significant one bit, rather than being interpreted as an operation, signals the end of the sequence.1For example, the following are equivalent:
(general-car-cdr object #b1011) (cdr (car (car object)))Here is a partial table of path/operation equivalents:
#b10 cdr #b11 car #b100 cddr #b101 cdar #b110 cadr #b111 caar #b1000 cdddr
(SRFI 1) This copies an arbitrary tree constructed from pairs, copying both the car and cdr elements of every pair. This could have been defined by
(define (tree-copy tree) (let loop ((tree tree)) (if (pair? tree) (cons (loop (car tree)) (loop (cdr tree))) tree)))
[1] Note that path is restricted to a machine-dependent range, usually the size of a machine word. On many machines, this means that the maximum length of path will be 30 operations (32 bits, less the sign bit and the “end-of-sequence” bit).