Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
axkr opened this issue Dec 8, 2021 · 3 comments

Comments

@axkr
Copy link

axkr commented Dec 8, 2021

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

Do I have to

  • copy all elements below the "insert point" into a new mutList
  • insert the new element at "insert point" in the mutList
  • copy all elements greater equal the "insert point" into the mutList
  • call mutList.immutable() at the end
@GlenKPeterson
Copy link
Owner

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
Copy link
Owner

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
Copy link
Author

axkr commented Dec 10, 2021

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

I opened this issue to track it in my project:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants