Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't dissoc implemented for vectors in clojure?

Tags:

clojure

I know that clojure's clojure.lang.IPersistentVector implements assoc, as in (assoc [0 1 2 3] 0 -1) ; => [-1 1 2 3]. I have also heard (as in this answer) that clojure's vector doesn't implement dissoc, as in (dissoc [0 1 2 3] 0) ; => [1 2 3]. If this functionality is so easily reproducible using subvec, is there any real reason why it shouldn't be implemented in clojure.lang, clojure.core, or even contrib? If not, is there any reasoning behind that?

like image 434
djhaskin987 Avatar asked Aug 29 '14 02:08

djhaskin987


1 Answers

Dissoc doesn't make much sense for vectors for two reasons:

  1. The meaning of dissoc is "remove a key". You can't remove a key from a vector without causing other side effects (e.g. moving all future values)
  2. dissoc would perform relatively badly on vectors if it had to move all subsequent keys - roughly O(n) with quite a lot of GC. Clojure core generally avoids implementing operations that aren't efficient / don't make sense for a particular data structure.

Basically, if you find yourself wanting to do dissoc on a vector, you are probably using the wrong data structure. A persistent hashmap or set is probably a better choice.

If you want a data structure which works as a vector but supports cutting out and inserting elements or subsequences efficiently, then it is worth checking out RRB trees: https://github.com/clojure/core.rrb-vector

like image 179
mikera Avatar answered Oct 03 '22 23:10

mikera