Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

= and == in Clojure

Tags:

clojure

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.

like image 756
Arun R Avatar asked Mar 02 '10 16:03

Arun R


People also ask

How do you check for equality in Clojure?

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 == .

What is a vector in Clojure?

Advertisements. A Vector is a collection of values indexed by contiguous integers. A vector is created by using the vector method in Clojure.

What is let 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.


2 Answers

== 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.

like image 81
Michał Marczyk Avatar answered Nov 09 '22 19:11

Michał Marczyk


== is a type independent way of comparing numbers

(== 3 3.0) ;=> true  (= 3 3.0) ;=> false 
like image 20
David Avatar answered Nov 09 '22 17:11

David