我想检查列表中的任何元素是否满足给定条件。 我尝试过使用 some,它返回 true 或 nil,但似乎找不到具有类似功能的函数来检索 true/false。
示例 - 检查列表中是否有 6:
(some #(= 6 %) numbers-list))
几年前我也有类似的愿望,为此目的编写了函数 has-some?,以及它的逆函数 has-none?。从单元测试来看:
(verify
(is= true (t/has-some? odd? [1 2 3]))
(is= false (t/has-some? odd? [2 4 6]))
(is= false (t/has-some? odd? []))
(is= false (t/has-none? odd? [1 2 3]))
(is= true (t/has-none? odd? [2 4 6]))
(is= true (t/has-none? odd? [])))
这些函数的目的是消除
some
和 some?
函数之间的歧义,以及 not-any?
与 any?
含义之间的疯狂(恕我直言)冲突。 clojure.core
中的这两个冲突很容易搬起石头砸自己的脚。
对我来说这也很奇怪,没有
any?
在“有任何?”的意义上。在 Clojure 中。
虽然那里有
not-any?
。
所以你只要补充它,你就拥有了你需要的
user> (def has-any? (complement not-any?))
#'user/has-any?
user> (has-any? #(= % 6) [1 2 3 4 5 6])
true
user> (has-any? #(= % 6) [1 2 3 4 5])
false
user> (has-any? #(= % 6) [])
false