Can you use the eq? procedure to test the equality of
pairs?
Not in the sense you probably have in mind. In spite of its name, what
eq? tests is identity rather than mere equality.
Remember that the identity of a pair in Scheme is fixed by the act of
construction rather than by its contents. The eq? procedure
can be used to test whether two expressions denote exactly the same pair,
the result of a single act of construction; but more often one wants to
check whether the contents of two separately constructed pairs are the
same.
Could you give some examples?
Sure. First, here's a case in which the same pair, resulting from a single act of construction, is denoted by two different expressions:
On the other hand, here's a case in which two pairs with the same components are constructed separately:> (define a (cons 1 2)) > (define b a) > (eq? a b) #t
What if the pairs are expressed by literals? Does determining the datum that a literal denotes involve a separate act of construction each time?> (define a (cons 1 2)) > (define b (cons 1 2)) > (eq? a b) #f
That's an interesting point. It's up to the Scheme implementer. Some implementations of Scheme, such as Elk and SCM, construct a new pair for each literal datum:
Other implementations, such as Scheme 48, compile tables of literal values and refer back to them if the same data are needed again; hence, these implementations perform only a single act of construction in evaluating such expressions:> (eq? '(1 . 2) '(1 . 2)) #f
Which is right, according to the Scheme standard?> (eq? '(1 . 2) '(1 . 2)) #t
The Scheme standard explicitly declines to rule on this point, leaving
implementers free to resolve it as they prefer. This means that the
programmer should not rely on either alternative. The eq?
procedure is required always to return a Boolean value, but in this case
(and several others) it is not required to return a particular
Boolean value.
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/pairs-and-eq-ques.html