在Clojure中的映射值上映射函数 [英] Mapping a function on the values of a map in Clojure
本文介绍了在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
已经存在?
推荐答案
我喜欢你的 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屋!
查看全文