Skip to content

Instantly share code, notes, and snippets.

@johnmastro
Last active May 14, 2019 08:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmastro/7224520 to your computer and use it in GitHub Desktop.
Save johnmastro/7224520 to your computer and use it in GitHub Desktop.
Filter Clojure maps by value
(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