kyle smith
unread,Jun 15, 2009, 10:28:06 PM6/15/09Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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))