Mapping a function on the values of a map in Clojure

前端 未结 11 1450
面向向阳花
面向向阳花 2020-11-29 16:03

I want to transform one map of values to another map with the same keys but with a function applied to the values. I would think there was a function for doing this in the c

11条回答
  •  清酒与你
    2020-11-29 16:45

    I'm a Clojure n00b, so there may well be much more elegant solutions. Here's mine:

    (def example {:a 1 :b 2 :c 3 :d 4})
    (def func #(* % %))
    
    (prn example)
    
    (defn remap [m f]
      (apply hash-map (mapcat #(list % (f (% m))) (keys m))))
    
    (prn (remap example func))
    

    The anon func makes a little 2-list from each key and its f'ed value. Mapcat runs this function over the sequence of the map's keys and concatenates the whole works into one big list. "apply hash-map" creates a new map from that sequence. The (% m) may look a little weird, it's idiomatic Clojure for applying a key to a map to look up the associated value.

    Most highly recommended reading: The Clojure Cheat Sheet .

提交回复
热议问题