Clojure 在向量中关联多个元素的惯用方法

Clojure 在向量中关联多个元素的惯用方法,clojure,clojurescript,Clojure,Clojurescript,我有一个一维向量,一个要在向量中更新的索引向量,以及一个应该与这些索引中的每一个相关联的值 我是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

我有一个一维向量,一个要在向量中更新的索引向量,以及一个应该与这些索引中的每一个相关联的值

我是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
在内部使用瞬态,这实际上可能比
reduce
版本更有效。既然不是这样,懒惰的序列开销可能会把它吃光

最后,一个暂时的版本:

(defn assoc-all
  [v ks value]
  (persistent!
    (reduce
      #(assoc! %1 %2 value)
      (transient v)
      ks)))