简体   繁体   English

在Clojure clojure.set / select vs. clojure.core / filter中过滤一组

[英]Filter a set in Clojure clojure.set/select vs. clojure.core/filter

I would like to filter a set, something like: 我想过滤一组,例如:

(filter-set even? #{1 2 3 4 5})
; => #{2 4}

If I use clojure.core/filter I get a seq which is not a set: 如果我使用clojure.core/filter我得到一个不是一个集合的seq:

(filter even? #{1 2 3 4 5})
; => (2 4)

So the best I came with is: 所以我带来的最好的是:

(set (filter even? #{1 2 3 4 5}))

But I don't like it, doesn't look optimal to go from set to list back to set. 但是我不喜欢它,从设置到列表再到设置看起来并不是最佳的。 What would be the Clojurian way for this ? Clojurian的方式是什么?

UPDATE UPDATE

I did the following to compare @A.Webb and @Beyamor approaches. 我做了以下比较@ A.Webb和@Beyamor方法。 Interestingly, both have almost identical performance, but clojure.set/select is slightly better. 有趣的是,两者的性能几乎相同,但clojure.set/select略胜一筹。

(defn set-bench []
  (let [big-set (set (take 1000000 (iterate (fn [x] (int (rand 1000000000))) 1)))]
    (time (set (filter even? big-set))) ; "Elapsed time: 422.989 msecs"
    (time (clojure.set/select even? big-set))) ; "Elapsed time: 345.287 msecs"
    nil) ; don't break my REPL !

clojure.set is a handy API for common set operations. clojure.set是一个用于常见集合操作的便捷API。

In this case, clojure.set/select is a set-specific filter. 在这种情况下, clojure.set / select是一个特定于集的过滤器。 It works by dissociating elements which don't meet the predicate from the given set. 它的工作原理是分离不符合给定集合谓词的元素。

(require 'clojure.set)

(clojure.set/select even? #{1 2 3 4 5})
; => #{2 4} 

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

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