为什么Clojure没有任何东西?或任何pred?功能?

Why does Clojure not have an any? or any-pred? function?

似乎我必须缺少一些明显的常用习语,但是缺少这两个功能对我来说有点困惑。有some,但它返回nil而不是False,为什么不提供any?函数?


some被认为与any?相同(如果存在)。有一个紧密命名的函数not-any?可以在幕后调用some

1
2
3
4
(source not-any?)
(def
...
not-any? (comp not some))

,您可以简单地将其写为:

1
(def any? (comp boolean some))

打补丁欢迎:

考虑到not-any?函数自1.0

1
2
3
4
5
(defn any? [pred col] (not (not-any? pred col)))
(any? even? [1 2 3])
true
(any? even? [1  3])
false

起就已经包含在其中,因此关于命名的观点尤其正确,我猜没有人可以发送在补丁中? (提示提示微移)

在使用基于some的任何代码时(not-any?会在后台调用某些内容)时,请小心匹配pred和col的类型,或者使用捕获了类型异常

1
2
3
(if (some odd? [2 2 nil 3]) 1 2)
No message.
  [Thrown class java.lang.NullPointerException]

ps:此示例来自clojure 1.2.1


nil的计算结果为false。 (if nil 1 2)的值为2。

some返回满足谓词的第一个元素。不是nilfalse的任何值都将计算为true。因此(if (some odd? [2 2 3]) 1 2)的值为1。


您正在寻找some-fn,尽管您将不得不通过boolean对它生成的谓词的返回值进行线程化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
user> (doc every-pred)
-------------------------
clojure.core/every-pred
([p] [p1 p2] [p1 p2 p3] [p1 p2 p3 & ps])
  Takes a set of predicates and returns a function f that returns true if all of its
  composing predicates return a logical true value against all of its arguments, else it returns
  false. Note that f is short-circuiting in that it will stop execution on the first
  argument that triggers a logical false result against the original predicates.
nil
user> (doc some-fn)
-------------------------
clojure.core/some-fn
([p] [p1 p2] [p1 p2 p3] [p1 p2 p3 & ps])
  Takes a set of predicates and returns a function f that returns the first logical true value
  returned by one of its composing predicates against any of its arguments, else it returns
  logical false. Note that f is short-circuiting in that it will stop execution on the first
  argument that triggers a logical true result against the original predicates.
nil

这些函数的用法与some相似。


随着Clojure 1.9的发布,这一情况发生了变化,该版本增加了any?函数,该函数在任何输入上都返回true。 pb> Re:someany?not-any?every?not-every?

请注意,此any?不是not-any?的取反,就像您可能会根据not-every?已实现,但是是一个全新的功能。如果要查找not-any?的求反(取消求反?),则使用的功能仍然是some


这些似乎是针对\\\\" any \\\\"。这个问题还提到\\\\" any-pred \\\\"这样的东西怎么样?

1
2
(defn any-pred [preds]
  (comp not (apply every-pred (map #(comp not %) preds))))

这需要一个集合而不是多个参数,但是更改它很容易。

示例:

1
2
3
4
=> (def p (any-pred [(partial ="a") (partial ="b")]))
=> (p"a")  true
=> (p"b")  true
=> (p"c")  false


您可以这样定义任何pred:

1
(defn any-pred [& preds] (complement (apply every-pred (map complement preds))))

or

1
(defn any-pred [& preds] (fn [v](boolean (some #(% v) preds))))