[英]clojure - delete an element from a ref vector
I'm using a vector of maps which defined as a referece. 我正在使用一个定义为参考的地图矢量。
i want to delete a single map from the vector and i know that in order to delete an element from a vector i should use subvec
. 我想从向量中删除单个地图,我知道为了从向量中删除元素,我应该使用
subvec
。
my problem is that i couldn't find a way to implement the subvec
over a reference vector. 我的问题是,我无法找到一个方法来实现
subvec
超过参考向量。 i tried to do it using: (dosync (commute v assoc 0 (vec (concat (subvec @v 0 1) (subvec @v 2 5)))))
, so that the seq returned from the vec
function will be located on index 0 of the vector but it didn't work. 我尝试使用:
(dosync (commute v assoc 0 (vec (concat (subvec @v 0 1) (subvec @v 2 5)))))
,以便从vec
函数返回的seq将位于向量的索引0但它不起作用。
does anyone have an idea how to implement this? 有没有人知道如何实现这个?
thanks 谢谢
commute (just like alter ) needs a function that will be applied to the value of the reference. commute (就像alter一样)需要一个将应用于引用值的函数。
So you will want something like: 所以你会想要这样的东西:
;; 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]
Note the that separating out the code to delete an element from the vector is a generally good idea for several reasons: 请注意,分离出代码以从向量中删除元素通常是个好主意,原因如下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.