clojure - 从ref向量中删除一个元素

I.N*_*.N. 7 vector clojure ref

我正在使用一个定义为参考的地图矢量.

我想从向量中删除单个地图,我知道为了从我应该使用的向量中删除元素subvec.

我的问题是我找不到一种方法来实现subvec参考向量.我尝试使用: (dosync (commute v assoc 0 (vec (concat (subvec @v 0 1) (subvec @v 2 5))))),以便从vec函数返回的seq 将位于向量的索引0,但它不起作用.

有没有人知道如何实现这个?

谢谢

mik*_*era 5

commute(就像alter一样)需要一个将应用于引用值的函数.

所以你会想要这样的东西:

;; define your ref containing a vector
(def v (ref [1 2 3 4 5 6 7]))

;; define a function to delete from a vector at a specified position
(defn delete-element [vc pos]
  (vec (concat 
         (subvec vc 0 pos) 
         (subvec vc (inc pos)))))

;; delete element at position 1 from the ref v
;; note that communte passes the old value of the reference
;; as the first parameter to delete-element
(dosync 
  (commute v delete-element 1))

@v
=> [1 3 4 5 6 7]
Run Code Online (Sandbox Code Playgroud)

请注意,分离出代码以从向量中删除元素通常是个好主意,原因如下:

  • 此功能可能在其他地方重复使用
  • 它使您的交易代码更短,更自我解释