map-in

73 views
Skip to first unread message

Steve Ashton

unread,
Mar 24, 2015, 10:16:58 PM3/24/15
to clo...@googlegroups.com
Is there anything for map which operates like update-in and assoc-in, where we can call a function with the value looked up in a nested structure?

What I've come up with:
(defn map-in
  "Returns a lazy sequence consisting of the results of
  calling map on coll, for each value in the coll,
  extracting the value using keys ks, finally applying f the
  that value and args: (apply f item args)"
  [coll [& ks] f & args]
  (map (fn [item]
         (let [value (reduce #(%2 %1) item ks)]
           (apply f value args)))
       coll))

Which could then be used like:
(def customers [{:name "Alice" :address {:city "Raleigh" :state "NC"}}
                {:name "Bob" :address   {:city "Seattle" :state "WA"}}])

(map-in customers [:address :state] #(-> % clojure.string/lower-case keyword))
=> (:nc :wa)

Just wondering if I am re-inventing something here.

Thanks,
Steve

Francis Avila

unread,
Mar 24, 2015, 11:44:54 PM3/24/15
to clo...@googlegroups.com
The reduce in your mapped function is already implemented by get-in. Other possible implementations using get-in:

(defn map-in [coll ks f & args]
 
(->> coll
       
(map #(get-in % ks))
       
(map #(apply f % args))))

Or:

(defn map-in [coll ks f & args]
 
(map #(apply f (get-in % ks) args) coll))

Reply all
Reply to author
Forward
0 new messages