Hammer and Tongs Map Replace

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)]

(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.



Filed under Clojure

2 responses to “Hammer and Tongs Map Replace

  1. 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))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s