2014-03-29 25 views
5

我有一維向量,向量中要更新的索引向量以及應與這些索引中的每一個相關聯的值。在向量中關聯多個元素的習慣方式

我是新來的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命令可以用來更新多個鍵或關聯集合中的索引,但我無法弄清楚使用關聯任意鍵或索引列表的語法魔法。

回答

8

使用reduce

(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))) 
相關問題