gpt4 book ai didi

clojure - 使用 clojure 中的函数映射转换映射

转载 作者:行者123 更新时间:2023-12-02 05:10:05 26 4
gpt4 key购买 nike

我正在尝试想出一种方法来转换 clojure HashMap ,方法是将来自另一个映射的函数应用于每个值。这是我到目前为止所拥有的:

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

这很好用,但前提是每个函数都接受一个参数,即键的当前值。如果我想在我的函数映射中放置一个函数,该函数使用与同一键中的值不同的值怎么办?例如,假设我想将键 :a:b 的和放入键 :d 中?

我可以尝试这样的事情:

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

但有没有办法改变我的 transform-map 函数,以便它在该函数调用中使用适当的参数?

最佳答案

我建议分解函数以及它们如何适用于转换映射。下面是一个例子来说明:

;; 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)

关于clojure - 使用 clojure 中的函数映射转换映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15626542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com