Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

jvm - (Boolean. false) in Clojure

According to http://hyperpolyglot.org/lisp, the only falsehoods in Clojure are false and nil. Indeed, surprisingly enough, (Boolean. false) is not false:

user=> (if (Boolean. false) 1 2)
1
user=> (not (Boolean. false))
false
user=> (false? (Boolean. false))
false

On the other hand, it somehow is false:

user=> (class false)
java.lang.Boolean
user=> (= false (Boolean. false))
true

This is rather counterintuitive. Are there reasons for this behaviour or was it simply overlooked?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can find the explanation at http://clojure.org/special_forms#if.

It's good to read the whole paragraph, but here's the crucial bit excerpted, emphasis added:

[...] All [...] conditionals in Clojure are based upon the same logic, that is, nil and false constitute logical falsity, and everything else constitutes logical truth, and those meanings apply throughout. [...] Note that if does not test for arbitrary values of java.lang.Boolean, only the singular value false (Java's Boolean.FALSE), so if you are creating your own boxed Booleans make sure to use Boolean/valueOf and not the Boolean constructors.

Compare

System.out.println(Boolean.valueOf(false) ? true : false);  // false
System.out.println(new Boolean(false)     ? true : false);  // false

with

user=> (if (Boolean/valueOf false) true false)
false
user=> (if (Boolean. false) true false)
true

Thus, (Boolean. false) is neither nil nor false, just as (Object.) is neither nil nor false. And as @Chiron has pointed out, it's bad practice to use it anyway.

As for (= false (Boolean. false)) being true, I think @looby's explanation is spot on: Since = relies on Java's equals method, the special semantics of conditionals in Clojure don't apply, and boolean equality will be as it is in Java.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...