Skip to content

Instantly share code, notes, and snippets.

@syou6162
Created May 22, 2012 12:36
Show Gist options
  • Save syou6162/2768796 to your computer and use it in GitHub Desktop.
Save syou6162/2768796 to your computer and use it in GitHub Desktop.
条件をどんどん付けてフィルタリングするのを簡単にするための何か
;; macroで書く必要がなかった...
;; (defmacro gen-bool-fns
;; [key-value-pairs]
;; `(loop [fns# []
;; pairs# (partition 2 ~key-value-pairs)]
;; (if (empty? pairs#)
;; fns#
;; (recur
;; (conj fns# (let [[k# v#] (first pairs#)]
;; (fn [x#] (= (k# x#) v#))))
;; (rest pairs#)))))
(defn gen-bool-fns
[key-value-pairs]
(loop [fns []
pairs (partition 2 key-value-pairs)]
(if (empty? pairs)
fns
(recur
(conj fns (let [[k v] (first pairs)]
(fn [x] (= (k x) v))))
(rest pairs)))))
(defstruct employee :name :a :b :c)
(defn conds-filter [lists & conds]
(->> lists
(filter
(fn [x] (reduce 'and (map (fn [f] (f x))
(gen-bool-fns conds)))))))
(def employee-a (struct-map employee :name :a :a 1 :b 2 :c 3))
(def employee-b (struct-map employee :name :b :a 1 :b 2 :c 3))
(def employee-c (struct-map employee :name :c :a 1 :b 2 :c 1))
(def employees [employee-a employee-b employee-c])
(conds-filter employees :a 1 :b 2 :c 3) ; ({:name :a, :a 1, :b 2, :c 3} {:name :b, :a 1, :b 2, :c 3})
(conds-filter employees :b 2) ; ({:name :a, :a 1, :b 2, :c 3} {:name :b, :a 1, :b 2, :c 3} {:name :c, :a 1, :b 2, :c 1})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment