The Grinnell Scheme Web: The eq?
procedure

Suppose I want to compare the values of two Boolean expressions, to find out whether they are the same or different. Isn't there a Boolean predicate that does this -- a kind of ``if and only if'' predicate?

The eq? predicate can be used to make such comparisons, although it is not a strictly Boolean predicate -- it can take values of any data type as operands. If you apply it to Boolean operands, though, you get the behavior you're looking for:

> (eq? #t #t)
#t
> (eq? #f #t)
#f
> (eq? #f #f)
#t
> (eq? (boolean? 5) (number? 5))
#f
What happens if you apply eq? to operands of other types?

The eq? procedure tests whether its two operands are exactly the same Scheme object -- not merely equal values, despite the name of the procedure, but a single instance of a single value. In some of Scheme's data types, it is possible to construct different instances of the same value, with different computational histories. The eq? procedure will distinguish these instances.

Can't the same Boolean value be constructed or computed in different ways? Couldn't there be different instances of the true Boolean value?

The Scheme standard implies that each of the Boolean values must be unique, however computed. If an implementation chooses to maintain multiple copies of a Boolean, this fact must be concealed from the Scheme programmer; eq? is not allowed to distinguish them.

But values of other data types are not necessarily unique in this way?

Booleans, symbols, and the empty list (the single value that constitutes Scheme's ``null'' data type) are guaranteed to be unique. Values of other data types can exist in multiple instances. The rule of thumb for programmers is that eq? is seldom useful except for Boolean and symbol operands.

What if the two operands in a single call to eq? are of different data types? Is that an error?

No. But eq? will always return the false Boolean value in such a case:

> (eq? 5 #t)
#f


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/eq-ques.html


created July 23, 1995
last revised December 27, 1995

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