我有一个一维向量、一个要在向量内更新的索引向量,以及一个应与每个索引关联的值。
我是 Clojure 的新手,想象一下可能有一种更惯用的方式来编写我最终得到的例程:
(defn update-indices-with-value [v indices value]
(loop [my-v v
my-indices indices
my-value value]
(if (empty? my-indices)
my-v
(recur (assoc my-v (peek my-indices) my-value)
(pop my-indices)
my-value))))
我知道 assoc 可用于更新关联集合中的多个键或索引,但我无法弄清楚将 assoc 与任意键或索引列表一起使用的语法魔法。
最佳答案
使用减少
:
(defn assoc-all
[v ks value]
(reduce #(assoc %1 %2 value) v ks))
示例:
(assoc-all [1 2 3 4] [0 1] 2)
;; => [2 2 3 4]
<小时/>
或者,创建键/值对并使用apply
:
(defn assoc-all
[v ks value]
(->> (interleave ks (repeat value))
(apply assoc v)))
如果 assoc
在内部使用 transient ,这实际上可能比 reduce
版本更有效。因为事实并非如此,惰性序列开销可能会耗尽所有资源。
所以,最后,一个临时版本:
(defn assoc-all
[v ks value]
(persistent!
(reduce
#(assoc! %1 %2 value)
(transient v)
ks)))
关于clojure - 在向量中关联多个元素的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22730726/