Clojure: How do I apply a function to a subset of the entries in a hash-map?

后端 未结 3 1163
鱼传尺愫
鱼传尺愫 2021-02-06 12:43

I am not to Clojure and attempting to figure out how to do this.

I want to create a new hash-map that for a subset of the keys in the hash-map applies a function to the

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-06 13:09

    The following seems to work:

    (defn doto-map [ks f amap]
      (into amap
        (map (fn [[k v]] [k (f v)])
             (filter (fn [[k v]] (ks k)) amap))))
    
    user=> (doto-map #{:hello :foo} (fn [k] (.toUpperCase k)) {:hello "World" :try "This" :foo "bar"})
    {:hello "WORLD", :try "This", :foo "BAR"}
    

    There might be a better way to do this. Perhaps someone can come up with a nice one-liner :)

提交回复
热议问题