Mapping a function on the values of a map in Clojure

前端 未结 11 1503
面向向阳花
面向向阳花 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:44

    (defn map-vals
      "Map f over every value of m.
       Returns a map with the same keys as m, where each of its values is now the result of applying f to them one by one.
       f is a function of one arg, which will be called which each value of m, and should return the new value.
       Faster then map-vals-transient on small maps (8 elements and under)"
      [f m]
      (reduce-kv (fn [m k v]
                   (assoc m k (f v)))
                 {} m))
    
    (defn map-vals-transient
      "Map f over every value of m.
       Returns a map with the same keys as m, where each of its values is now the result of applying f to them one by one.
       f is a function of one arg, which will be called which each value of m, and should return the new value.
       Faster then map-vals on big maps (9 elements or more)"
      [f m]
      (persistent! (reduce-kv (fn [m k v]
                                (assoc! m k (f v)))
                              (transient {}) m)))
    

提交回复
热议问题