caar, cadr, cdar, cddr - compositions of car and cdr
LIBRARY
(import (rnrs)) ;R6RS
(import (rnrs base)) ;R6RS
(import (scheme r5rs)) ;R7RS
(import (scheme base)) ;R7RS
SYNOPSIS
(caar pair)
(cadr pair)
(cdar pair)
(cddr pair)
DESCRIPTION
These procedures are compositions of car and cdr as follows:
(define (caar x) (car (car x)))
(define (cadr x) (car (cdr x)))
(define (cdar x) (cdr (car x)))
(define (cddr x) (cdr (cdr x)))
These procedures can also be used with lists, which in Scheme are
linked lists of pairs.
The caar and cdar procedures return the car and cdr fields
of the first element of the list.
The cadr procedure returns the second element of the list. The
cddr procedure returns the tail of the tail of the list.
There are two conventions for building lists where these
procedures often show up. An
association list
or
alist
associates a key in the car field with a value in the cdr field, see
assq(3scm).
A
property list
or
plist
also associates a key with a value, but it uses a flat
structure, see
memq(3scm).
RETURN VALUES
Returns the contents of the car or cdr field of the pair which is
in the car or cdr field of the argument.
EXAMPLES
(caar '((a . b) (d . e) (g . h))) => a
(cdar '((a . b) (d . e) (g . h))) => b
(cadr '(a b c)) => b
(cddr '(a b c)) => (c)
(map cadr '((a b) (d e) (g h))) => (b e h)
APPLICATION USAGE
These procedures should primarily be used when walking lists or
conventional list structures like alists.
It can be tempting to write code that stores data as a new kind of
tree of pairs and uses these procedures to walk that tree. While it is
possible, it quickly becomes hard to follow. In modern code it is
often better to define a new data type with
define-record-type(3scm).
An alternative is to use a pattern matching library like Alex Shinn's
widely available
(chibi match).
COMPATIBILITY
Most Lisp systems provide these procedures.
ERRORS
This procedure can raise exceptions with the following condition types:
- &assertion (R6RS)
-
The wrong number of arguments was passed, an argument was not a pair
or a referenced car or cdr field did not contain a pair.
- R7RS
-
The assertions described above are errors.
Implementations may signal an error, extend the procedure's
domain of definition to include such arguments,
or fail catastrophically.
SEE ALSO
car(3scm)
STANDARDS
R4RS,
IEEE Scheme,
R5RS,
R6RS,
R7RS
HISTORY
Present in MIT AI Memo No.~7 (1958 or 1959).
AUTHORS
This page is part of the
scheme-manpages
project.
It includes materials from the RnRS documents.
More information can be found at
https://github.com/schemedoc/manpages/
.
Markup created by unroff 1.0sc, March 04, 2023.