Clojure 中“some”的替代函数,返回 true 或 false

问题描述 投票:0回答:3

我想检查列表中的任何元素是否满足给定条件。 我尝试过使用 some,它返回 truenil,但似乎找不到具有类似功能的函数来检索 true/false

示例 - 检查列表中是否有 6:

(some #(= 6 %) numbers-list))

clojure
3个回答
5
投票

这是我认为最惯用的方法(使用 set 作为函数),但这确实返回

nil
或值本身:

(some #{6} [1 2 3 4 5 6 7])
;; => 6

正如对您问题的评论中提到的,可以使用

boolean
将其转换为布尔值。

返回布尔值的其他方法是转换为集合并使用

contains?
返回布尔值:

(contains? (set [1 2 3 4 5 6 7]) 6)
;; => true

(因为

contains?
“对于数字索引集合,例如 向量和 Java 数组,...测试数字键是否在 索引范围。”)需要额外的转换。

或者类似地使用 Java 互操作(但也适用于向量和列表):

(.contains [1 2 3 4 5 6 7] 6)
;; => true

另请参阅测试列表是否包含 Clojure 中的特定值


1
投票

几年前我也有类似的愿望,为此目的编写了函数 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
中的这两个冲突很容易搬起石头砸自己的脚。


1
投票

对我来说这也很奇怪,没有

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
© www.soinside.com 2019 - 2024. All rights reserved.