Pairs are built into the Scheme language. For historical reasons, pairs are created with the cons built-in function, and the elements of a pair are accessed with car and cdr:
(define x (cons 1 2))
x
(1 . 2)
(car x)
1
(cdr x)
2
Recursive lists are also built into the language, using pairs. A special value denoted nil or ’() represents the empty list. A recursive list value is rendered by placing its elements within parentheses, separated by spaces:
(cons 1(cons 2(cons 3(cons 4 nil))))
(1 2 3 4)
(list 1 2 3 4)
(1 2 3 4)
(define one-through-four (list 1 2 3 4))
(car one-through-four)
1
(cdr one-through-four)
(2 3 4)
(car (cdr one-through-four))
2
(cons 10 one-through-four)
(10 1 2 3 4)
(cons 5 one-through-four)
(5 1 2 3 4)
Whether a list is empty can be determined using the primitive null? predicate. Using it, we can define the standard sequence operations for computing length and selecting elements:
(define (length items)(if (null? items)0
(+ 1 (length (cdr items)))))(define (getitem items n)(if (= n 0)(car items)(getitem (cdr items) (- n 1))))(define squares (list 1 4 9 16 25))
(length squares)
5
(getitem squares 3)
16