Last active
May 14, 2019 08:35
-
-
Save johnmastro/7224520 to your computer and use it in GitHub Desktop.
Filter Clojure maps by value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn filter-by-val-1 | |
[pred m] | |
(into {} (filter (fn [[k v]] (pred v)) | |
m))) | |
;; This one is a little faster | |
(defn filter-by-val-2 | |
[pred m] | |
(persistent! | |
(reduce-kv (fn [acc k v] | |
(if (pred v) | |
(conj! acc [k v]) | |
acc)) | |
(transient {}) | |
m))) | |
;; Usage, removing nil and zero values | |
;; (see http://stackoverflow.com/questions/19669917/clojure-hashmaps-as-generalized-vectors): | |
(filter-by-val-2 #(and (not (nil? %)) | |
(not (zero? %))) | |
{:x 1 :y nil}) ;=> {:x 1} | |
;; The complete answer to the question might end up looking like this: | |
(defn filter-vals | |
[pred m] | |
(into {} (filter (fn [[k v]] (pred v)) | |
m))) | |
(defn gen+ | |
[m1 m2] | |
(letfn [(keep-val? [val] | |
(and (not (nil? val)) | |
(not (zero? val))))] | |
(merge-with + | |
(filter-vals keep-val? m1) | |
(filter-vals keep-val? m2)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment