我有一个我想要过滤的集合。过滤器使用映射完成,其中键是集合项中的属性,值是集合项应匹配的值。例如:
Dispose()
现在,我已经构建了我的过滤器功能,只采用一个属性和值。我想将其扩展为实际上能够使用过滤器(let [filters {:name "test"
:type "new"}
collection [{:name "testable" :type "old"}
{:name "shoudwork" :type "new"}
{:name "testable" :type "new"}]])
。
这是我目前的过滤器:
hashmap
换句话说,我希望(filter #(re-find (re-pattern "test") (string/lower-case (% :name))) collection)
不对filter
进行硬编码,但它应该是"test
let绑定的值,而filters
来自不是硬编码到(% :name)
,而是:name
让绑定的关键。
答案 0 :(得分:3)
创建一个函数,返回单个[key expected-value]的过滤函数:
(defn regex-value [[k expected-rex]]
(fn [c] (re-find (re-pattern expected-rex)
(clojure.string/lower-case (get c k)))))
创建一个将创建复合过滤条件的函数:
(defn build-filter [filters]
(apply every-pred (map regex-value filters)))
使用它:
(let [filters {:name "test"
:type "new"}
collection [{:name "testable" :type "old"}
{:name "shoudwork" :type "new"}
{:name "testable" :type "new"}]]
(filter (build-filter filters) collection))
答案 1 :(得分:3)
你也可以使用传感器:
;; first you create a filtering step factory for transduction:
(defn make-filter [[k v]]
(filter #(re-find (re-pattern v)
(clojure.string/lower-case (k %)))))
;; and then transform the collection:
(let [filters {:name "test"
:type "new"}
collection [{:name "testable" :type "old"}
{:name "shoudwork" :type "new"}
{:name "testable" :type "new"}]]
(sequence (reduce comp (map make-filter filters)) collection))