Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure Remove item from Vector at a Specified Location

Tags:

vector

clojure

Is there a way to remove an item from a vector based on index as of now i am using subvec to split the vector and recreate it again. I am looking for the reverse of assoc for vectors?

like image 447
Hamza Yerlikaya Avatar asked Sep 08 '09 16:09

Hamza Yerlikaya


2 Answers

subvec is probably the best way. The Clojure docs say subvec is "O(1) and very fast, as the resulting vector shares structure with the original and no trimming is done". The alternative would be walking the vector and building a new one while skipping certain elements, which would be slower.

Removing elements from the middle of a vector isn't something vectors are necessarily good at. If you have to do this often, consider using a hash-map so you can use dissoc.

See:

  • subvec at clojuredocs.org
  • subvec at clojure.github.io, where the official website points to.
like image 170
Brian Carper Avatar answered Sep 23 '22 02:09

Brian Carper


(defn vec-remove   "remove elem in coll"   [pos coll]   (into (subvec coll 0 pos) (subvec coll (inc pos)))) 
like image 37
zenna Avatar answered Sep 24 '22 02:09

zenna