Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Clojure's identical? function only return true if the things being compared are actually the same instance?

Tags:

clojure

I thought

(identical? x y)

only returns true if both x and y are the same instance? So what about this:

(def moo 4)
(def cow 4)

(identical? moo cow)
true

Yet I thought both moo and cow are separate instances of the integer '4'? What gives?

like image 850
Zuriar Avatar asked Sep 14 '14 11:09

Zuriar


1 Answers

In JVM two equal integers between -128 and 127 are always identical, because it maintains IntegerCache.

It means that two equal integers between -128 and 127 are always the same instance of Integer class.

Try comparing different integers:

(identical? 4 (+ 2 2)) ; true
(identical? 127 127) ; true
(identical? 128 128) ; false

See this answer on Code Golf for more info.

like image 54
Leonid Beschastny Avatar answered Oct 25 '22 15:10

Leonid Beschastny