【问题标题】:Idiomatic way to assoc multiple elements in vector在向量中关联多个元素的惯用方式
【发布时间】:2014-05-08 23:18:30
【问题描述】:

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

我是 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 与任意键或索引列表一起使用的语法魔法。

【问题讨论】:

    标签: clojure clojurescript


    【解决方案1】:

    使用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)))
    

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 2017-08-05
      • 2020-10-21
      • 1970-01-01
      相关资源
      最近更新 更多