The Grinnell Scheme Web: The cons
procedure

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:

> (cons 1 2)
(1 . 2)
> (cons #t #f)
(#t . #f)
> (cons (+ 7 14 21) (odd? 38))
(42 . #f)
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.)

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:

> (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)
Show me how you'd use this to return two values from a procedure.

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


created August 4, 1995
last revised December 26, 1995

Copyright 1995 by John David Stone (stone@math.grin.edu)