(布尔值.假)在 Clojure 中 [英] (Boolean. false) in Clojure
问题描述
根据 http://hyperpolyglot.org/lisp,Clojure 中唯一的错误是 false
和 nil
.事实上,令人惊讶的是,(Boolean.false)
不是假的:
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?
推荐答案
你可以在 http://找到解释clojure.org/special_forms#if.
阅读整个段落很好,但这里摘录了关键部分,并添加了重点:
It's good to read the whole paragraph, but here's the crucial bit excerpted, emphasis added:
[...] Clojure 中的所有 [...] 条件都基于相同的逻辑,即 nil 和 false 构成逻辑错误,一切else 构成逻辑真理,这些含义贯穿始终.[...] 请注意,if 不会测试 java.lang.Boolean 的任意值,仅测试奇异值 false(Java 的 Boolean.FALSE),因此,如果您要创建自己的盒装布尔值,请确保使用 Boolean/valueOf 而不是 Boolean 构造函数.
[...] 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.
比较
System.out.println(Boolean.valueOf(false) ? true : false); // false
System.out.println(new Boolean(false) ? true : false); // false
与
user=> (if (Boolean/valueOf false) true false)
false
user=> (if (Boolean. false) true false)
true
因此,(Boolean.false)
既不是 nil
也不是 false
,就像 (Object.)
既不是 nil
也不是 false
.正如@Chiron 指出的那样,无论如何使用它都是不好的做法.
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.
至于 (= false (Boolean. false))
为真,我认为 @looby 的解释是正确的:因为 =
依赖于 Java 的 equals
方法,Clojure 中条件的特殊语义不适用,布尔相等将与 Java 中相同.
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.
这篇关于(布尔值.假)在 Clojure 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!