2012-02-15 28 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