Why does Clojure not have an any? or any-pred? function?
似乎我必须缺少一些明显的常用习语,但是缺少这两个功能对我来说有点困惑。有
1 2 3 4 | (source not-any?) (def ... not-any? (comp not some)) |
,您可以简单地将其写为:
1 | (def any? (comp boolean some)) |
打补丁欢迎:
考虑到
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 |
起就已经包含在其中,因此关于命名的观点尤其正确,我猜没有人可以发送在补丁中? (提示提示微移)
在使用基于
1 2 3 | (if (some odd? [2 2 nil 3]) 1 2) No message. [Thrown class java.lang.NullPointerException] |
ps:此示例来自clojure 1.2.1
您正在寻找
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 |
这些函数的用法与
随着Clojure 1.9的发布,这一情况发生了变化,该版本增加了
请注意,此
这些似乎是针对\\\\" 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)))) |