Clojure not nil check



在 Clojure 中nil?检查 nil。如何检查不是零?

我想做以下Java代码的Clojure等效项:

if (value1==null && value2!=null) {
}

跟进:我希望进行不为零的检查,而不是用not包裹它。 if有一个if-not对应物。nil?有这样的对应物吗?

在 Clojure 1.6 之后,您可以使用some?

(some? :foo) => true
(some? nil) => false

这很有用,例如,作为谓词:

(filter some? [1 nil 2]) => (1 2)

定义not-nil?的另一种方法是使用 complement 函数,它只是反转布尔函数的真实性:

(def not-nil? (complement nil?))

如果要检查多个值,请使用not-any?

user> (not-any? nil? [true 1 '()])
true
user> (not-any? nil? [true 1 nil])
false 
如果您对区分

falsenil不感兴趣,则可以仅使用该值作为条件:

(if value1
   "value1 is neither nil nor false"
   "value1 is nil or false")

在 Clojure 中,nil 对于条件表达式而言算作 false

因此(not x)在大多数情况下,工作实际上与(nil? x)完全相同(布尔值 false 除外)。

(not "foostring")
=> false
(not nil)
=> true
(not false)  ;; false is the only non-nil value that will return true
=> true

因此,要回答您最初的问题,您可以执行以下操作:

(if (and value1 (not value2)) 
   ... 
   ...)

条件:(and (nil? value1) (not (nil? value2)))

如果条件:(if (and (nil? value1) (not (nil? value2))) 'something)

编辑:Charles Duffy 为not-nil?提供了正确的自定义定义:

你想要一个不为零的?轻松完成:(def not-nil? (comp not nil?))

如果您希望您的测试在给定false时返回true,那么您需要此处的其他答案之一。 但是,如果您只想测试每当传递 nilfalse 以外的内容时返回一个真实值,您可以使用 identity . 例如,要从序列中剥离nil s(或 false s),请执行以下操作:

(filter identity [1 2 nil 3 nil 4 false 5 6])
=> (1 2 3 4 5 6)

你可以试试 when-not :

user> (when-not nil (println "hello world"))
=>hello world
=>nil
user> (when-not false (println "hello world"))
=>hello world
=>nil
user> (when-not true (println "hello world"))
=>nil

user> (def value1 nil)
user> (def value2 "somevalue")
user> (when-not value1 (if value2 (println "hello world")))
=>hello world
=>nil
user> (when-not value2 (if value1 (println "hello world")))
=>nil
如果你

想要一个not-nil?函数,那么我建议按如下方式定义它:

(defn not-nil? 
  (^boolean [x]
    (not (nil? x)))

话虽如此,值得将其用法与明显的替代方案进行比较:

(not (nil? x))
(not-nil? x)

我不确定引入额外的非标准函数是否值得保存两个字符/一个嵌套级别。如果您想在高阶函数等中使用它,这将是有意义的。

还有一个选项:

(def not-nil? #(not= nil %))

最新更新