On REPL, if I define
(def fits (map vector (take 10 (iterate inc 0))))
and then call
(== [2] (nth fits 2))
I get false.
But
(= [2] (nth fits 2))
returns true.
Is this expected ? I tried (class [2]) and (class (nth fits 2) and both return Persistent Vector.
Unlike Java's equals method, Clojure's = returns true for many values that do not have the same type as each other. = does not always return true when two numbers have the same numeric value. If you want to test for numeric equality across different numeric categories, use == .
Advertisements. A Vector is a collection of values indexed by contiguous integers. A vector is created by using the vector method in Clojure.
Clojure let is used to define new variables in a local scope. These local variables give names to values. In Clojure, they cannot be re-assigned, so we call them immutable.
==
is for comparing numbers. If either of its arguments is not a number, it will always return false:
(== :a :a) ; => false
As you can see by saying (clojure.contrib.repl-utils/source ==)
at the REPL (with repl-utils
require
'd, of course), ==
calls the equiv
method of clojure.lang.Numbers
. The relevant bit of clojure/lang/Numbers.java
(from the latest or close-to-latest commit on GitHub):
static public boolean equiv(Object x, Object y){ return y instanceof Number && x instanceof Number && equiv((Number) x, (Number) y); }
Use =
for equality comparisons of things which may not be numbers. When you are in fact dealing with numbers, ==
ought to be somewhat faster.
== is a type independent way of comparing numbers
(== 3 3.0) ;=> true (= 3 3.0) ;=> false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With