Clojure:在 collection 中找到第一个通过谓词真值测试的事件

Clojure: find the first occurence in a collection that passes predicate truth test

Clojure 中有没有像标题中描述的那样工作的函数:

考虑这个向量:

(def v [{:a 0 :b 1} {:a 0 :b 3} {:a 0 :b 2}])

我正在尝试捕捉第一个条目,其中 :b 等于 3。

用法如下:(这就是 JS-underscore 查找的工作方式)

(myfind #(= (:b %) 3) v)

天真的解决方案:

(first (filter #(= (:b %) 3) v))

惯用的解决方案:

(some #(when (= (:b %) 3) %) v)

作为函数:

(defn myfind [pred coll]                                                                                                          
  (some #(when (pred %) %) coll))

(myfind #(= (:b %) 3) v) => {:b 3, :a 0}

安东:

您没有具体说明是要 return 匹配的整个地图还是某个键的某个值。否则:

(filter #(= (:b %) 3)  [{:a 0 :b 1} {:a 0 :b 3} {:a 0 :b 2}])
=> ({:a 0, :b 3})