3.8 Pairs and Lists
A pair joins two arbitrary values. The cons procedure constructs pairs, and the car and cdr procedures extract the first and second elements of the pair, respectively. The pair? predicate recognizes pairs.
Some pairs print by wrapping parentheses around the printed forms of the two pair elements, putting a . between them.
Examples: |
> (cons 1 2) |
(1 . 2) |
((1 . 2) . 3) |
1 |
2 |
#t |
A list is a combination of pairs that creates a linked list. More precisely, a list is either the empty list null, or it is a pair whose first element is a list element and whose second element is a list. The list? predicate recognizes lists. The null? predicate recognizes the empty list.
A list prints as a pair of parentheses wrapped around the list elements.
Examples: |
> null |
() |
(0 1 2) |
#t |
#t |
#f |
An expression with ' followed by the printed form of a pair or list produces a pair or list constant.
Examples: |
> '() |
() |
> '(1 . 2) |
(1 . 2) |
> '(1 2 3) |
(1 2 3) |
Pairs are immutable (contrary to Lisp tradition), and pair? and list? recognize immutable pairs and lists, only. The mcons procedure creates a mutable pair, which works with set-mcar! and set-mcdr!, as well as mcar and mcdr.
Examples: |
> p |
{1 . 2} |
> (pair? p) |
#f |
> (mpair? p) |
#t |
> (set-mcar! p 0) |
> p |
{0 . 2} |
Among the most important predefined procedures on lists are those that iterate through the list’s elements:
| |||
(1 1/2 1/3) | |||
| |||
#f | |||
| |||
#t | |||
| |||
(1 2) | |||
| |||
16 | |||
| |||
123 | |||
| |||
("Keys" "U.S.A.") | |||
| |||
(where "Florida") |
Pairs and Lists in Reference: PLT Scheme provides more on pairs and lists.