O'Reilly logo

Clojure Programming by Brian Carper, Christophe Grand, Chas Emerick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Equality and Equivalence

Clojure provides three ways to determine the equality of values, which are embodied in three different predicate functions.

Object Identity (identical?)

Object identity, implemented by identical? in Clojure, is used to determine if two (or more) objects are exactly the same instance. This corresponds directly to == in Java (when used to compare object references), is in Python, and equal? in Ruby:

(identical? "foot" (str "fo" "ot"))
;= false
(let [a (range 10)]
  (identical? a a))
;= true

In general, numbers will never be identical?, even if provided as literals:

(identical? 5/4 (+ 3/4 1/2))
;= false
(identical? 5.4321 5.4321)
;= false
(identical? 2600 2600)
;= false

The exception is that the JVM (and therefore Clojure) provides for a limited range of fixnums. Fixnums are a pool of boxed integer values that are always used in preference to allocating a new integer. Ruby’s fixnum semantics cover the entire range of its integers, while Python’s fixnums are available only between –5 and 256.[337] The Oracle JVM’s fixnum range is ±127[338] and so only results of operations that return integers within this range may be identical? to other integers of the same value:

(identical? 127 (dec 128))
;= true
(identical? 128 (dec 129))
;= false

In general, it’s wise to not use identical? at all when comparing numbers.

Reference Equality (=)

This is what is most commonly referred to as “equality”: a (potentially) type-sensitive, deep comparison of values to determine if they are structurally ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required