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:
(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 (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 (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.
A triple is a Pair whose second cell is a Pair.
A quadruple is a Pair whose second cell is a triple.
A quintuple is a Pair whose second cell is a quadruple.
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
triple-third for this construct.