简体   繁体   English

在Clojure中将多个过滤器应用于鹅口疮中的集合

[英]Applying multiple filters to a collection in a thrush in Clojure

The following code 以下代码

(let [coll [1 2 3 4 5]
      filters [#(> % 1) #(< % 5)]]
  (->> coll
       (filter (first filters))
       (filter (second filters))))

Gives me 给我

(2 3 4)

Which is great, but how do I apply all the filters in coll without having to explicitly name them? 哪个好,但是如何在coll中应用所有过滤器而不必明确命名它们?

There may be totally better ways of doing this, but ideally I'd like to know an expression that can replace (filter (first filters)) (filter (second filters)) above. 可能有更好的方法来做到这一点,但理想情况下我想知道一个可以替换(过滤器(第一个过滤器))(过滤器(第二个过滤器))的表达式。

Thanks! 谢谢!

Clojure 1.3有一个新的every-pred函数,你可以这样使用:

(filter (apply every-pred filters) coll)

This should work :- 这应该工作: -

(let [coll [1 2 3 4 5]
      filters [#(> % 1) #(< % 5)]]
  (filter (fn [x] (every? #(% x) filters)) coll)
)

I can't say I'm very proud of the following, but at least it works and allows for infinite filters: 我不能说我为以下内容感到自豪,但至少它可以工作并允许无限过滤器:

(seq 
  (reduce #(clojure.set/intersection 
          (set %1) 
          (set %2)) (map #(filter % coll) filters)))

If you can use sets in place of seqs it would simplify the above code as follows: 如果您可以使用集合代替seqs,它将简化上述代码,如下所示:

(reduce clojure.set/intersection (map #(filter % coll) filters))
(let [coll [1 2 3 4 5]
      filters [#(> % 1) #(< % 5)]]
  (reduce (fn [c f] (filter f c)) coll filters))

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

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