Skip to content

Commit

Permalink
feat: HashSet.all/any (#5582)
Browse files Browse the repository at this point in the history
I think the overhead (runtime/later proving) of using `for` is paid off
by being able to short-circuit.

These functions are needed downstream to switch over the Std.HashSet.
  • Loading branch information
kim-em authored Oct 2, 2024
1 parent 478a34f commit 1329a26
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Std/Data/HashSet/Basic.lean
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,18 @@ instance [BEq α] [Hashable α] {m : Type v → Type v} : ForM m (HashSet α) α
instance [BEq α] [Hashable α] {m : Type v → Type v} : ForIn m (HashSet α) α where
forIn m init f := m.forIn f init

/-- Check if all elements satisfy the predicate, short-circuiting if a predicate fails. -/
@[inline] def all (m : HashSet α) (p : α → Bool) : Bool := Id.run do
for a in m do
if ¬ p a then return false
return true

/-- Check if any element satisfies the predicate, short-circuiting if a predicate succeeds. -/
@[inline] def any (m : HashSet α) (p : α → Bool) : Bool := Id.run do
for a in m do
if p a then return true
return false

/-- Transforms the hash set into a list of elements in some order. -/
@[inline] def toList (m : HashSet α) : List α :=
m.inner.keys
Expand Down
16 changes: 16 additions & 0 deletions tests/lean/run/hashmap.lean
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,22 @@ def addKeyToState (k : Nat) : StateM Nat PUnit := do
ans := k :: ans
return ans

/-- info: true -/
#guard_msgs in
#eval m.any fun x => x > 4

/-- info: false -/
#guard_msgs in
#eval m.any fun x => x = 0

/-- info: true -/
#guard_msgs in
#eval m.all fun x => x < 2^30

/-- info: false -/
#guard_msgs in
#eval m.all fun x => x > 4

/-- info: [1000000000, 2, 1] -/
#guard_msgs in
#eval m.toList
Expand Down

0 comments on commit 1329a26

Please sign in to comment.