我正在使用定义为引用的 map 向量。
我想从向量中删除单个 map ,我知道为了从向量中删除一个元素,我应该使用 subvec
.
我的问题是我找不到实现 subvec
的方法在引用向量上。
我尝试使用:(dosync (commute v assoc 0 (vec (concat (subvec @v 0 1) (subvec @v 2 5)))))
,以便从 vec
返回 seq函数将位于向量的索引 0 上,但它不起作用。
有没有人知道如何实现这一点?
谢谢
最佳答案
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]
请注意,出于以下几个原因,从向量中分离出删除元素的代码通常是一个好主意:
关于vector - clojure - 从引用向量中删除一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9293017/