[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Are `eqv?' and `eq?' the same?
From: |
Pascal J. Bourguignon |
Subject: |
Re: Are `eqv?' and `eq?' the same? |
Date: |
Sun, 25 Aug 2013 14:39:13 +0200 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/24.2 (gnu/linux) |
Alexandru Cojocaru <address@hidden> writes:
> Hi,
>
> from the GUILE manual [0]:
>
> `eq?' tests just for the same object (essentially a pointer
> comparison)
> `eqv?' extends `eq?' to look at the value of numbers and
> characters.
>
> this is what I get:
>
> scheme@(guile-user)> (eq? 3 (+ 1 2))
> $1 = #t
>
> is this behavior intentional or some type of bug?
Yes.
A some implementations internalize small integers (and characters).
A lot of implementations even don't allocate small integers (fixnums) as
objects, but encode them instead as immediate values.
So:
(let ((x 3)
(y (+ 1 2)))
(eq? x y))
could be represented in memory in different ways:
+-------+
x: | f:3 |
+-------+
y: | f:3 |
+-------+
+-------+
x: | p0---|----------+
+-------+ |
y: | p0---|--------+ |
+-------+ | |
| |
v v
+----------+
| f:3 |
+----------+
+-------+
x: | p1---|-----------------------------+
+-------+ |
y: | p2---|--------+ |
+-------+ | |
| |
v v
+----------+ +----------+
| f:3 | | f:3 |
+----------+ +----------+
This later case would occur if the number was a bignum:
b:391278903129038129038129038901238901 for example.
(f: denotes the type tag for fixnums, b: the type tag for bignums).
Now, even if we're in the second situation, for example, we could get
it also with: (let ((x 3) (y x)) (eq? x y)), it is still possible that
in the process of calling a function such as eq? the argument be copied,
so that in
(define (eq? a b) …)
we could get a situation like:
+-------+
a: | p1---|-----------------------------+
+-------+ |
b: | p2---|--------+ |
+-------+ | |
| |
v v
+----------+ +----------+
| f:3 | | f:3 |
+----------+ +----------+
even starting from the second or (less probable) first situation!
Now, if inside eq? we have the first or second situation, then the
result will be #t, and in the third situation, the result will be #f.
That's all you learn from eq?, which, for characters and numbers, is not
much interesting: it only tells you something about how numbers are
implemented and processed by the implementation.
--
__Pascal Bourguignon__
http://www.informatimago.com/