Convert map with function mapping in clojure

I am trying to come up with a way to convert the hash of a clojure file by applying a function from a different map to each value. Here is what I still have:

(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}

This works fine, but only as long as each function takes one argument, which is the current key value. What if I want to put a function in my function map that uses values โ€‹โ€‹different from those in the same key? For example, suppose I want to put the amount of keys :aand :bin the key :d?

I can try something like:

(assoc fm :d (fn[a b] (+ a b)))

but is there a way to change my function transform-mapso that it uses the appropriate arguments in the call to that function?

+2
source share
2

. , , :

;; functions which take 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)
+4

, , :

", : a : b : d?"

user> (def m {:a 0 :b 0 :c 0 :d 0}
#'user/m 
user> (reduce #(%2 %1) m [#(assoc % :a (inc (:a %))) 
                          #(assoc % :b (inc (:b %))) 
                          #(assoc % :d (+ (:a %) (:b %)))]) 
{:a 1, :c 0, :b 1, :d 2} 

, (assoc) (:b ..) , . , , , .

[target action], :

user> (reduce (fn [result [target action]] 
                  (assoc result target (action result))) 
                 m 
                 [[:a #(inc (:a %))] 
                  [:b #(inc (:b %))] 
                  [:d #(+ (:a %) (:b %))]])
{:a 1, :c 0, :b 1, :d 2}
0

Source: https://habr.com/ru/post/1658382/


All Articles