5.2.2 Triples to octuples

Pairs are useful for representing data that is composed of two parts such as a calendar date (composed of a number and month), or a playing card (composed of a rank and suit). But, what if we want to represent data composed of more than two parts such as a date (composed of a number, month, and year) or a poker hand consisting of five playing cards? For more complex data structures, we need data structures that have more than two components.

A triple has three components. Here is one way to define a triple datatype:

(define (make-triple a b c)
        (lambda (w) (if (= w 0) a (if (= w 1) b c))))
(define (triple-first t) (t 0))
(define (triple-second t) (t 1))
(define (triple-third t) (t 2))

Since a triple has three components we need three different selector values. Another way to make a triple would be to combine two Pairs. We do this by making a Pair whose second cell is itself a Pair:

(define (make-triple a b c) (cons a (cons b c)))
(define (triple-first t) (car t))
(define (triple-second t) (car (cdr t)))
(define (triple-third t) (cdr (cdr t)))

Similarly, we can define a quadruple as a Pair whose second cell is a triple:

(define (make-quad a b c d) (cons a (make-triple b c d)))
(define (quad-first q) (car q))
(define (quad-second q) (triple-first (cdr q))
(define (quad-third q) (triple-second (cdr q))
(define (quad-fourth q) (triple-third (cdr q))

We could continue in this manner defining increasingly large tuples.

  1. A triple is a Pair whose second cell is a Pair.

  2. A quadruple is a Pair whose second cell is a triple.

  3. A quintuple is a Pair whose second cell is a quadruple.

  4. $\cdots $

  5. An $n+1$-uple is a Pair whose second cell is an n-uple.

Building from the simple Pair, we can construct tuples containing any number of components.

Exercise 5.8.  Define a procedure that constructs a quintuple and procedures for selecting the five elements of a quintuple.

Exercise 5.9.  Another way of thinking of a triple is as a Pair where the first cell is a Pair and the second cell is a scalar. Provide definitions of make-triple, triple-first, triple-second, and triple-third for this construct.