Mapping a function on the values of a map in Clojure

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

    I like your reduce version. With a very slight variation, it can also retain the type of records structures:

    (defn map-function-on-map-vals [m f]
      (reduce (fn [altered-map [k v]] (assoc altered-map k (f v))) m m))
    

    The {} was replaced by m. With that change, records remain records:

    (defrecord Person [firstname lastname])
    
    (def p (map->Person {}))
    (class p) '=> Person
    
    (class (map-function-on-map-vals p
      (fn [v] (str v)))) '=> Person
    

    By starting with {}, the record loses its recordiness, which one might want to retain, if you desire the record capabilities (compact memory representation for instance).

提交回复
热议问题