A pair is a data structure that holds two values. Once the pair is created, it cannot be changed (meaning, it is immutable). A pair is made with cons. A pair is printed like a list, but with a dot between the two values:
1 2 3 4 | '(42 . 43) '("see" . "saw") '(this . that) '(#<procedure:+> . #<procedure:->) |
cons is the inverse of car and cdr, so this identity is true for every pair:
For instance:
pair? is the predicate function.
Pairs can be combined to make other data structures. For instance, under the hood, lists (other than the empty list) are made from a series of linked pairs, where the final element is null. The list function itself is just shorthand for an equivalent series of nested cons operations:
Because every non-empty list is a pair, + For this reason, the pair? predicate can be used to test for a non-empty list. functions that work on pairs—including cons, car, and cdr—will also work on non-empty lists:
If you need to store two values, there’s nothing wrong with using a pair directly instead of a list. This can be worthwhile in situations that call for pecunious use of computing resources, because a two-element list uses two pairs rather than one (and thus twice as much memory and allocation time). Keep in mind that because of this extra pair, the cdr of a list always returns a list, whereas in a pair it returns a single value:
The names of cons, car, and cdr are conventional and historic. In the original Lisp interpreter of 1958, cons was chosen as an abbreviation for “construct”. car and cdr were abbreviations for “contents of the address part of the register” and “contents of the decrement part of the register”, terminology specific to the IBM 704 computer that ran the interpreter. At this point, they’re unlikely to be dislodged.
Pairs and Lists in the Racket Guide
Pairs, Lists, and Racket Syntax in the Racket Guide