Hammer and Tongs Map Replace
Posted: January 19, 2013 Filed under: Clojure | Tags: Clojure 2 Comments »Probably the last thing I want to do from a performance point of view is to replace one map key’s value, especially in a sequence of sequences, where the sequences are maps. But given Clojure’s nth can lead to positional dependencies in code, I have most recently been creating a sequence of maps, so that I can more easily manipulate database information, specifically going from our Board of Assessor’s database into the tax billing database.
However, I needed to trim one key in the Assessor’s data, the user’s account number, so I could search the tax billing system to see if the key (property or personal property account) existed. I could have done this as the maps were being created, but I am actually reusing a lot of Clojure code, and Clojure coding seems to pride itself on simpler functions, rather than the sandwich with all the trimmings (or Big Mac) approach.
So, here are my examples:
(defn trim-map-key
"Takes a map, a key, applies cstr/trim to that key's value, and returns the replaced map."
[in-map in-key]
(let [old-val (in-key in-map)
replace-val (cstr/trim old-val)
out-map (assoc in-map in-key replace-val)]
out-map))
(defn trim-map-key-in-sos
"Takes a sequence of maps, runs trim-map-key over every map in the sequence using the supplied key."
[s-o-m replace-key]
(map #(trim-map-key % replace-key) s-o-m))
So, calling trim-map-key-in-sos on a sequence of maps will result in {…, :user_acct_no “ 28″, …} turning into {…, :user_acct_no “28″, …} for each map in the sequence.
Clojure has a function that’s a generalization of trim-map-key: update-in. I think trim-map-key could be written as (defn trim-map-key [in-map in-key] (update-in in-map [in-key] cstr/time))
Thanks. This is very helpful.