Skip to content

Commit

Permalink
Add TreapSet.containsAny (#18)
Browse files Browse the repository at this point in the history
Checks if a predicate evaluates to `true` for any element in the set,
using a recursive tree traversal. Short-circuits the search as soon as
any element results in `true`.
  • Loading branch information
ericeil authored Dec 14, 2024
1 parent 889dfe2 commit a5f3410
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ internal class EmptyTreapSet<@Treapable E> private constructor() : TreapSet<E>,
override fun contains(element: E): Boolean = false
override fun containsAll(elements: Collection<E>): Boolean = elements.isEmpty()
override fun containsAny(elements: Iterable<E>): Boolean = false
override fun containsAny(predicate: (E) -> Boolean): Boolean = false
override fun findEqual(element: E): E? = null
override fun forEachElement(action: (element: E) -> Unit): Unit {}
override fun remove(element: E): TreapSet<E> = this
Expand Down
9 changes: 9 additions & 0 deletions collect/src/main/kotlin/com/certora/collect/HashTreapSet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,15 @@ internal class HashTreapSet<@Treapable E>(
}
return result!!
}

override fun containsAny(predicate: (E) -> Boolean): Boolean {
forEachNodeElement {
if (predicate(it)) {
return true
}
}
return left?.containsAny(predicate) == true || right?.containsAny(predicate) == true
}
}

internal interface ElementList<E> {
Expand Down
3 changes: 3 additions & 0 deletions collect/src/main/kotlin/com/certora/collect/SortedTreapSet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,7 @@ internal class SortedTreapSet<@Treapable E>(
override fun arbitraryOrNull(): E? = treapKey
override fun shallowForEach(action: (element: E) -> Unit): Unit { action(treapKey) }
override fun <R : Any> shallowMapReduce(map: (E) -> R, reduce: (R, R) -> R): R = map(treapKey)

override fun containsAny(predicate: (E) -> Boolean): Boolean =
predicate(treapKey) || left?.containsAny(predicate) == true || right?.containsAny(predicate) == true
}
7 changes: 7 additions & 0 deletions collect/src/main/kotlin/com/certora/collect/TreapSet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ public sealed interface TreapSet<out T> : PersistentSet<T> {
*/
public fun containsAny(elements: Iterable<@UnsafeVariance T>): Boolean

/**
Checks if this set contains any element that satisfies the given [predicate].
This traverses the treap without allocating temporary storage, which may be more efficient than [any].
*/
public fun containsAny(predicate: (T) -> Boolean): Boolean

/**
If this set contains exactly one element, returns that element. Otherwise, throws [NoSuchElementException].
*/
Expand Down

0 comments on commit a5f3410

Please sign in to comment.