为什么有些? returns Clojure 中参数为false 时为true?

Why some? returns true when it takes false as a parameter in Clojure?

我无法理解 Clojure 中 some? 函数的意图。

我需要一些函数(内置),当需要(nil 或 false)时 returns false。

示例如下:

(some? "1")
=> true

(some? nil)
=> false

(some? false) ;;Which is odd!!
=> true

不知道some?为什么会这样。但是你要找的是 boolean.


  1. https://clojuredocs.org/clojure.core/boolean

查看some?的文档:

(some? x)

Returns true if x is not nil, false otherwise.

false 绝对不是 nil 因此 (some? false) returns true.

它是nil?

的补充
(= (some? x) (not (nil? x))

正如@delta 所建议的,您可以使用 boolean 来检查是否有内容不是 nilfalse.

有效的source for some?

(defn some? [x] (not (nil? x)))

最好称为 not-nil?Tupelo 提供别名。

正如其他人所说,您要查找的函数是boolean

更简单,使用IF

user=> (if "1" true false)
true
user=> (if nil true false)
false
user=> (if false true false)
false

虽然有不止一种方法可以满足您的要求,但我认为最简单的方法是使用 truthy?falsey? 函数 from the Tupelo library:

The Truth Is Not Ambiguous

Clojure marries the worlds of Java and Lisp. Unfortunately, these two worlds have different ideas of truth, so Clojure accepts both false and nil as false. Sometimes, however, you want to coerce logical values into literal true or false values, so we provide a simple way to do that:

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

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

因为真实?和假的?是函数(而不是特殊形式或宏),我们可以将它们用作过滤器的参数或任何其他需要高阶函数的地方:

(def data [true :a 'my-symbol 1 "hello" \x false nil] )

(filter truthy? data)
;=> [true :a my-symbol 1 "hello" \x]
(filter falsey? data)
;=> [false nil]

(is (every? truthy? [true :a 'my-symbol 1 "hello" \x] ))
(is (every? falsey? [false nil] ))

(let [count-if (comp count keep-if) ]
  (let [num-true    (count-if truthy? data)   ; <= better than (count-if boolean data)
        num-false   (count-if falsey? data) ] ; <= better than (count-if not     data)
    (is (and  (= 6 num-true)
              (= 2 num-false) )))))