always-merge-with

0 views
Skip to first unread message

kyle smith

unread,
Jun 15, 2009, 10:28:06 PM6/15/09
to Clojure
I needed the functionality of merge-with, but need f applied in all
cases. This version only works for 2 maps, but you can use reduce for
more maps. This lets me incrementally build up maps whose vals can be
seqs.


(defn always-merge-with [f amap bmap]
"Like merge-with, but always applies f"
(loop [bkeys (keys bmap)
bvals (vals bmap)
result amap]
(if (nil? bkeys)
result
(let [bkey (first bkeys)
bval (first bvals)]
(recur (next bkeys) (next bvals)
(merge result {bkey (f (get amap bkey) bval)}))))))

(defn wrap-merge [amap bmap]
"If key doesn't exist in amap, wraps val from bmap in [].
Useful when incrementally merging a seq of vals into hashmaps when
the vals can be seqs themselves."
(always-merge-with #(if (nil? %1) [%2] (conj %1 %2)) amap bmap))
Reply all
Reply to author
Forward
0 new messages