如果 nil 在 Clojure 中被视为逻辑假,为什么 (false? nil) return false

If nil is treated as a logical false in Clojure, why does (false? nil) return false

Living Clojure 解释了类型 nil 被视为逻辑错误。

所以我预计 (false? nil) 到 return true,但事实并非如此。 (true? nil) 也没有。 return false,这让我认为 Clojure 既不将 nil 视为 true 也不将 false.

视为

另一方面,(not nil) 的计算结果为 true。所以我有点困惑。

根据 documentation of false?:

Returns true if x is the value false, false otherwise.

所以函数检查参数是否等于值 false 而不是检查它是否为 logically false.

在 Clojure 中,所有值要么在逻辑上为真,要么在逻辑上为假,因此可以在条件表达式中使用它们。唯一逻辑错误的值是 nilfalse.

区别在于测试逻辑真理,与价值本身。

nilfalse 在 Clojure 中被视为 逻辑错误。所有其他值都被视为 逻辑上为真

谓词 false?true? 分别显式测试 falsetrue,如您所述.这些谓词在 Clojure 中不常使用。

已经有一些不错的答案了。

人们有时会使用术语 falseynilfalse)和 truthy(所有其他值) 来描述 Clojure 值。 将值强制转换为布尔值 truefalse 有时很方便。我什至为此写了a handy function

(defn truthy?
  "Returns true if arg is logical true (neither nil nor false); otherwise returns false."
  [arg]
  (if arg true false))

(defn falsey?
  "Returns true if arg is logical false (either nil or false); otherwise returns false. Equivalent
   to (not (truthy? arg))."
  [arg]
  (if arg false true))

在过滤值或构造 true/false 值的向量时,这些有时很方便。 后来,我发现 Clojure 已经有一个函数 booleantruthy?.

做同样的事情

请务必查看 this list of documentation sources,尤其是 Clojure CheatSheet。享受吧!

The book Living Clojure explains that the type nil is treated the same as logical false.

首先,nil 是一个值 - 而不是类型。

  • 它的类型是无名的。
  • 任何引用(对象)类型都可以将其作为值。

其次,nilfalse 是不同的值。您可以轻松编写以不同方式对待它们的代码:

(map #(case %, nil 1, false 2) [nil false])
=> (1 2)

nil,例如双关语为空序列,

(count nil)
=> 0

false 没有

(count false)
Execution error ...

作为if的第一个参数,nil等价于false

释义the official document

(if test then else?)

... evaluates test, then ...

  • if it is nil or false, evaluates and yields else;
  • otherwise evaluates and yields then.

If else is not supplied, it defaults to nil.

All of the other conditionals (when, if-let, cond, ...) follow the same logic:

  • nil and false constitute logical falsity;
  • everything else constitutes logical truth.

至于谓词函数false?,可能已经定义好了...

(defn false? [x]
  (case x, false true, false))

... 对于除确切值 false、returns false.

之外的任何参数

顺便说一下,Clojure 值 falsetrue 是 Java 对象 Boolean/FALSEBoolean/TRUE:

Boolean/FALSE
=> false
(if Boolean/FALSE 1 2)
=> 2
(type false)
=> java.lang.Boolean