= and == in Clojure

烈酒焚心 提交于 2019-12-21 06:47:21

问题


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.


回答1:


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




回答2:


== is a type independent way of comparing numbers

(== 3 3.0)
;=> true

(= 3 3.0)
;=> false


来源:https://stackoverflow.com/questions/2364566/and-in-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!