Question

    > (eq? 1 1)
    #t
    > (eq? 1.1 1.1)
    #f
    > (= 1.1 1.1)
    #t

This is the interaction window in DrScheme. Could somebody please explain the difference between = and eq? in Scheme?

Was it helpful?

Solution

= compares numbers. eq? tests if the parameters represent the same data object in memory. eqv? should work in the second case as it tests same as eq? but tests primitives specially. More on equlivence predicates in scheme here.

OTHER TIPS

I would guess that since

eq? evaluates to #f unless its parameters represent the same data object in memory;

and

Scheme stores inexact numbers (1.1) differently from exact numbers (1)

The two 1.1 arguments do not reside in the same place in memory and return #f for eq?

Wikipedia Reference

eq? on numbers is unpredictable. It's up to the implementation or not whether numeric literals are interred so that the same numbers are in the same location in memory. The Racket language, for example, has recently chosen to intern such literals during reading. http://www.mail-archive.com/dev@racket-lang.org/msg04893.html

You won't know for sure whether or not your language implementation's runtime will represent each number uniquely. This can affect values that are boxed, like floats and bignums. That's why = exists as a predicate for numbers: it checks for the equal-ness of the content, rather than shallow pointer equality.

This isn't exclusive to languages like Scheme: equality vs equalness occurs in Python (is vs. ==) for example.

first difference: eq? works with any pair of values, while = works with any number of numbers.

there are several other equivalence predicates. Most of them only accept exactly two parameters. = is defined in the 'numbers' chapter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top