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

发布于 2025-01-06 13:22:00 字数 323 浏览 3 评论 0原文

我正在使用定义为参考的地图向量。

我想从向量中删除单个映射,并且我知道为了从向量中删除元素,我应该使用 subvec

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

有谁知道如何实现这个?

谢谢

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.

my problem is that i couldn't find a way to implement the subvec over a reference vector.
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.

does anyone have an idea how to implement this?

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

分开我的手 2025-01-13 13:22:00

通勤(就像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]

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

  • 该函数可能在其他地方重用
  • 它使您的事务代码更短且更具自我描述性

commute (just like alter) needs a function that will be applied to the value of the reference.

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:

  • This function is potentially re-usable elsewhere
  • It makes your transaction code shorter and more self-desciptive
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文