GlenKPeterson / Paguro

Generic, Null-safe, Immutable Collections and Functional Transformations for the JVM
Other
312 stars 24 forks source link

ImList, MutList - example for best practice of inserting an element before an existing element #45

Closed axkr closed 2 years ago

axkr commented 2 years ago

Is there an example for best practice of inserting an element before an existing element in ImList, MutList?

Do I have to

GlenKPeterson commented 2 years ago

Sorry I couldn't get back to you sooner - on vacation. Clojure's PersistentVector is different from Java's ArrayList in that it does not support random insertion (in other ways as well). However, the RRB-Tree in Paguro (and a different one in Clojure) does. RrbTree in this project has .insertAt(T, int) that should do what you need. The way your question is worded may also require .indexOf(Object).

GlenKPeterson commented 2 years ago

Another option (off the top of my head) is to use Paguro's transforms, but this is at least O(n) (RRB-Tree is O(log n):

myVec.take(idx)
     .append(myItem)
     .concat(myVec.drop(idx))
     .toImList()

That should work with mutable or immutable.

axkr commented 2 years ago

Ok I'm using RRB-Tree now and that seems to work.

I opened this issue to track it in my project: