简体   繁体   English

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

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

Is there a function in Clojure that works as described in the title: Clojure中是否有一个功能可以如标题中所述工作:

Consider this vector: 考虑这个向量:

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

I'm, trying to catch the first entry, in which :b equals 3. 我正在尝试捕获第一个条目,其中:b等于3。

Usage would be like so: (this is how the JS-underscore find works) 用法如下所示:(这是JS下划线查找的工作方式)

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

Naive solution: 天真的解决方案:

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

Idiomatic solution: 惯用的解决方案:

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

As a function: 作为功​​能:

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

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

Anton: 安东:

You did not specific if you wanted to return the whole map that matches or some value for a key. 如果要返回匹配的整个映射或某个键的某个值,则没有具体说明。 Otherwise: 除此以外:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM