在矢量中关联多个元素的惯用法

use*_*829 5 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
      (recur (assoc my-v (peek my-indices) my-value)
             (pop my-indices)
             my-value)))) 
Run Code Online (Sandbox Code Playgroud)

我知道assoc可以用来更新关联集合中的多个键或索引,但我无法弄清楚使用与任意键或索引列表关联的语法魔法.

xsc*_*xsc 8

用途reduce:

(defn assoc-all
  [v ks value]
  (reduce #(assoc %1 %2 value) v ks))
Run Code Online (Sandbox Code Playgroud)

例:

(assoc-all [1 2 3 4] [0 1] 2)
;; => [2 2 3 4]
Run Code Online (Sandbox Code Playgroud)

或者,创建键/值对并使用apply:

(defn assoc-all
  [v ks value]
  (->> (interleave ks (repeat value))
       (apply assoc v)))
Run Code Online (Sandbox Code Playgroud)

如果assoc在内部使用瞬态,这实际上可能比reduce版本更有效.因为它不是,懒惰的序列开销可能正在吃它.

所以,最后,一个瞬态版本:

(defn assoc-all
  [v ks value]
  (persistent!
    (reduce
      #(assoc! %1 %2 value)
      (transient v)
      ks)))
Run Code Online (Sandbox Code Playgroud)