Skip to content
Permalink
Browse files

ConsPStack.minusAll() will reuse structure when possible, a la #86

  • Loading branch information
hrldcpr committed Jan 29, 2020
1 parent aed1a71 commit 4720fa7e5b104ac77e342b9da98b86a7cf134099
Showing with 12 additions and 6 deletions.
  1. +12 −6 src/main/java/org/pcollections/ConsPStack.java
@@ -208,14 +208,20 @@ public void set(final E o) {

public ConsPStack<E> minusAll(final Collection<?> list) {
// TODO wrap list in a Set to speed up contains()?
// TODO re-use existing suffix stack after the last removed element
if (list.isEmpty()) return this;

ConsPStack<E> reversed = empty();
ConsPStack<E> suffix = this;
while (suffix.size > 0) {
if (!list.contains(suffix.first)) reversed = reversed.plus(suffix.first);
suffix = suffix.rest;
ConsPStack<E> kept = empty();
ConsPStack<E> searching = this;
ConsPStack<E> reversed = kept;
ConsPStack<E> suffix = searching;
while (searching.size > 0) {
final E e = searching.first;
searching = searching.rest;
if (list.contains(e)) {
// checkpoint only when we actually remove something, so we can reuse existing suffix stack
reversed = kept;
suffix = searching;
} else kept = kept.plus(e);
}
return suffix.plusAll(reversed); // plusAll reverses again
}

0 comments on commit 4720fa7

Please sign in to comment.
You can’t perform that action at this time.