How do you construct a pair?
With the cons procedure. It takes two arguments -- the two
values to be packed into the pair -- and returns the newly constructed
pair. For instance:
When the interpreter prints out a pair, it encloses the contents of the pair in parentheses and places a dot between them. (At least, it does this if the second component of the pair is an integer or a Boolean. In some other cases, such as when the second component of the pair is also a pair, there is a different convention for printing that we'll have to talk about later.)> (cons 1 2) (1 . 2) > (cons #t #f) (#t . #f) > (cons (+ 7 14 21) (odd? 38)) (42 . #f)
So a pair can be a component of another pair?
Sure -- either component of a pair can be anything, including another pair. You can nest them to arbitrary depths:
Show me how you'd use this to return two values from a procedure.> (cons (cons 1 2) 3) ((1 . 2) . 3) > (cons (cons (cons (cons (cons 1 2) 3) 4) 5) 6) (((((1 . 2) . 3) . 4) . 5) . 6)
OK. Let's suppose we want to write a variation of the prime? procedure that returns both a
Boolean indicating whether the argument is prime and an integer that is its
smallest prime divisor. We could rewrite the code this way:
; This procedure presupposes that lower-bound is odd.
(define (has-no-odd-divisor-in-range? n lower-bound upper-bound)
(if (< upper-bound lower-bound)
(cons #t n) ; range exhausted; no divisor found
(if (divisible? n lower-bound)
(cons #f lower-bound) ; divisor found
(has-no-odd-divisor-in-range? n (+ lower-bound 2) upper-bound))))
(define (prime? n)
(if (even? n)
(cons (= n 2) 2)
(has-no-odd-divisor-in-range? n 3 (integer-square-root n))))
Next topic
Previous topic
Table of contents
This document is available on the World Wide Web as
http://www.math.grin.edu/~stone/scheme-web/cons.html