使用clojure中的函数映射来转换地图 [英] Transforming a map with a map of functions in clojure
问题描述
我试图想出一种方法来转换clojure hashmap通过应用于每个值从另一个地图的函数。这是我到目前为止:
(defn transform-map [m fm]
(into {} [fv] m]
(let [mfn(get fm k identity)] [k(mfn v)]))
(def m {:a 0:b 0: c 0:d 0})
(def fm {:a inc:b dec:c identity})
(transform-map m fm); => {:a 1,:b -1 ,:c 0,:d 0}
这很好,但只要每个函数一个单独的参数是键的当前值如果我想在我的函数映射中使用除了在同一个键之外的值的函数如果我想把键的总和<$ :d
?::a
和:b
p>
我可以尝试类似:
(assoc fm:d [ab](+ ab)))
但是有一种方法可以改变我的 transform-map
函数,因此它将在该函数调用中使用适当的参数。
我建议分解这些函数以及它们如何在转换图中应用。下面是一个示例:
;函数需要一些参数并返回结果
(defn sub [ ab]( - ab))
(defn add [ab](+ ab))
数据映射
(def data {:a 5:b 4:c 3 })
; transformation map key =>输出键,值是函数的向量
;应用和函数将从数据映射获取的参数
(def transformations {:a [inc:a]
:b [dec: b]
:c [add:a:b]
:d [sub:b:c]})
;转换函数
(defn transform- map [m fm]
(into {}(map(fn [[kv]]
[k(apply(first v)
(apply juxt(rest v))m) ])fm)))
(transform-map数据转换)
I'm trying to come up with a way to transform a clojure hashmap by applying to each value a function from another map. Here's what I have so far:
(defn transform-map [m fm]
(into {} (for [[k v] m]
(let [mfn (get fm k identity)] [k (mfn v)])))
(def m {:a 0 :b 0 :c 0 :d 0})
(def fm {:a inc :b dec :c identity})
(transform-map m fm) ;=> {:a 1, :b -1, :c 0, :d 0}
That's works fine, but only so long as each function takes a single argument that is the current value of the key. What if I want to put a function in my function map that uses values other than those in the same key? For example, suppose I want to put the sum of the keys :a
and :b
into the key :d
?
I can try something like:
(assoc fm :d (fn[a b] (+ a b)))
but is there a way I can alter my transform-map
function so it will use the appropriate arguments in that function call?
I would suggest to decompose the functions and how they are applicable in the transformation map. Below is an example to show that:
;functions which takes some params and return a result
(defn sub [a b] (- a b))
(defn add [a b] (+ a b))
;data map
(def data {:a 5 :b 4 :c 3})
;transformation map key => output key, value is vector of function
;to apply and the params that function will take from the data map
(def transformations {:a [inc :a]
:b [dec :b]
:c [add :a :b]
:d [sub :b :c]})
;The transformation function
(defn transform-map [m fm]
(into {} (map (fn [[k v]]
[k (apply (first v)
((apply juxt (rest v)) m))]) fm)))
(transform-map data transformations)
这篇关于使用clojure中的函数映射来转换地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!