Clojure 中的(布尔值.假) [英] (Boolean. false) in Clojure

查看:26
本文介绍了Clojure 中的(布尔值.假)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 http://hyperpolyglot.org/lisp,Clojure 中唯一的谎言是 falsenil.确实,令人惊讶的是,(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 中的所有 [...] 条件都基于相同的逻辑,即 nilfalse 构成逻辑错误,并且所有else 构成逻辑真理,这些含义自始至终都适用.[...] 注意 if 不测试 java.lang.Boolean 的任意值,只测试奇异值 false(Java 的 Boolean.FALSE),因此,如果您要创建自己的盒装布尔值,请确保使用 Boolean/valueOf 而不是布尔构造函数.

[...] 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆