将函数映射到 Clojure 中的映射值 [英] Mapping a function on the values of a map in Clojure
问题描述
我想将一个值映射转换为另一个具有相同键但应用到值的函数的映射.我认为 clojure api 中有一个函数可以执行此操作,但我一直找不到它.
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}
有人知道 map-function-on-map-vals
是否已经存在吗?我认为确实如此(可能还有一个更好的名字).
Does anybody know if map-function-on-map-vals
already exists? I would think it did (probably with a nicer name too).
推荐答案
我喜欢你的 reduce
版本就好了.我认为这是惯用的.无论如何,这是一个使用列表理解的版本.
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)])))
这篇关于将函数映射到 Clojure 中的映射值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!