It seems kind of odd, kind of asymmetrical, that a Scheme procedure can take any number of operands but can return only one result.
Well, there are some implementations of Scheme that provide for multiple-result procedures, and it's possible that they'll be added in some future revision of the standard. But for now, if you're at all concerned about writing portable programs, you'll just have to live with the asymmetry.
But what is the programmer supposed to do if she writes a procedure that computes two or more values? Isn't there any way to communicate them to the caller?
Actually, there is a way. In addition to simple data values, such as integers and Booleans, Scheme provides data structures -- containers into which the programmer can pack data, thus making one out of many.
And a Scheme procedure can return a data structure?
That's right. There are some languages, such as Pascal, in which procedures can return only simple data values; but in Scheme a procedure can return anything.
So if a programmer wanted to return two computed values, she'd pack them into a data structure and return that instead?
That's right, and the caller would have to unpack it to get at the results. Sometimes it seems a little cumbersome, but generally it's straightforward. Then, again, there are a lot of cases in which the caller doesn't need to unpack the data structure, which may be passed around among several procedures before any of its contents are needed.
If you have exactly two values to pack together, the best data structure to use is a pair -- a container designed specifically to hold two values. The two values packed into a pair are completely independent of one another; they need not belong to the same data type. It is possible to put the same value into both positions in a pair.
Once constructed, a pair is a new datum, which can be passed to procedures and returned from procedures just like any other datum. You should note, however, that two pairs that are constructed on different occasions do not count as identical even if their contents are identical; a pair's identity is constituted by the act of construction, not by its contents.
The following pages explain how to construct and operate on pairs.
Table of contents
This document is available on the World Wide Web as
Copyright 1995 by John David Stone (firstname.lastname@example.org)