Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a function on the values of a map in Clojure

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 clojure api, but I have been unable to find it.

Here's an example implementation of what I'm looking for

(defn map-function-on-map-vals [m f]
  (reduce (fn [altered-map [k v]] (assoc altered-map k (f v))) {} m))
(println (map-function-on-map-vals {:a "test" :b "testing"} #(.toUpperCase %)))
{:b TESTING, :a TEST}

Does anybody know if map-function-on-map-vals already exists? I would think it did (probably with a nicer name too).

like image 722
Thomas Avatar asked Nov 04 '09 21:11

Thomas


2 Answers

I like your reduce version just fine. I think it's idiomatic. Here's a version using list comprehension anyways.

(defn foo [m f]
  (into {} (for [[k v] m] [k (f v)])))
like image 198
Brian Carper Avatar answered Oct 18 '22 15:10

Brian Carper


You can use the clojure.algo.generic.functor/fmap:

user=> (use '[clojure.algo.generic.functor :only (fmap)])
nil
user=> (fmap inc {:a 1 :b 3 :c 5})
{:a 2, :b 4, :c 6}
like image 45
Arthur Edelstein Avatar answered Oct 18 '22 16:10

Arthur Edelstein