2012-02-15 59 views
7

我正在使用定义为参考的地图向量。clojure - 删除参考向量中的元素

我想从矢量中删除一张地图,我知道为了从矢量中删除一个元素,我应该使用subvec

我的问题是,我找不到在参考矢量上实现subvec的方法。 我试图使用: (dosync (commute v assoc 0 (vec (concat (subvec @v 0 1) (subvec @v 2 5))))),这样从vec函数返回的seq将位于向量的索引0上,但它不起作用。

没有人有一个想法如何实现这个?

感谢

+0

使用矢量来存储您想要以随机访问方式删除的内容通常是错误的选择 - 它们无法高效地执行,因此用于执行此操作的语言功能很尴尬。考虑只是使用list/seq来代替。 – amalloy 2012-02-15 19:18:27

回答

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] 

注意的是分离出来的代码从向量删除元素是以下几个原因,总体上是好的主意:

  • 此功能潜在地在其他地方重复使用
  • 它使您的交易代码更短,更自我放松
+0

'(count vc)'作为'(subvec vc)' – 2012-02-15 13:26:47

+0

的第三个参数是多余的,更新和感谢! – mikera 2012-02-15 13:32:51

+0

感谢您的答案和提示。 – 2012-02-15 16:24:15