I’m learning conditional expression and have found eq?
and eqv?
has different behavior on integers and floats.
(define a 1.5)
(define b 1.5)
(eq? a b) ;; #f
(eqv? a b) ;; #t
(define a 1)
(define b 1)
(eq? a b) ;; #t
(eqv? a b) ;; #t
So is it safe to say Guile will store same integers in the same memory location?
1 Like
So is it safe to say Guile will store same integers in the same memory location?
Not in general, no. What you are noticing is that fixnums can be eq?
. Fixnums are small integers that can fit within a single machine word and thus are not heap allocated. How big the fixnum space is depends on the machine (much larger fixnum space on 64-bit machines than 32-bit, for example.)
How big is the fixnum space?
I’ve tried a very large number it still returns #t
(define a #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
(define b #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
(eq? a b)
=> #t
My machine is 64-bit. Shouldn’t it be 2^63?
You’re comparing literals so those will end up referring to the same heap allocated bignum when compiling that program.
For contrast, here’s an example of when they are not eq?
:
scheme@(guile-user)> (define a #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
scheme@(guile-user)> (define b #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
scheme@(guile-user)> (eq? a b)
$8 = #f
How big is the fixnum space?
It’s (1- word-size)
so you are right, it’s 63 bits on a 64-bit machine. Fixnums are tagged with a 0
in the least significant bit.
That’s to say Guile will compile code when executing a script and it will do some optimizations causing different behaviors from REPL. Just like gcc -O option.
That’s absolutely mental strike to me . Curious whether Python also have similar feature. It seems Python won’t enable optimizing when executing a script.
I guess I don’t really see the GCC connection. What you’re seeing is an implementation detail. The moral of the story here is that eq?
tests object identity AKA it’s memory address. It answers the question: “Does A refer to the same object that B refers to?” If you need to compare numbers for numeric equality, you should use =
or eqv?
.
2 Likes