5.2.1 Making pairs

Although Scheme provides the built-in procedures cons, car, and cdr for creating Pairs and accessing their cells, there is nothing magical about these procedures. We can define procedures with the same behavior ourselves using the subset of Scheme introduced in Chapter 3.

Here is one way to define the pair procedures (we prepend an s to the names to avoid confusion with the built-in procedures):

(define (scons a b) (lambda (w) (if w a b)))
(define (scar pair) (pair true))
(define (scdr pair) (pair false))

The scons procedure takes the two parts of the Pair as inputs, and produces as output a procedure. The output procedure takes one input, a selector that determines which of the two cells of the Pair to output. If the selector is true, the value of the if expression is the value of the first cell; if the selector is false, it is the value of the second cell. The scar and scdr procedures apply a procedure constructed by scons to either true (to select the first cell in scar) or false (to select the second cell in scdr).

Exercise 5.6. Convince yourself the definitions of scons, scar, and scdr above work as expected by following the evaluation rules to evaluate

(scar (scons 1 2))

Exercise 5.7. Show the corresponding definitions of tcar and tcdr that provide the pair selection behavior for a pair created using tcons defined as:

(define (tcons a b) (lambda (w) (if w b a)))