Lean4
/-- O(log n). Modify an element in the set with the given function,
doing nothing if the key is not found.
Note that the element returned by `f` must be equivalent to `x`.
updateWith f 0 {1, 2, 3} = {1, 2, 3}
updateWith f 1 {1, 2, 3} = {2, 3} if f 1 = none
= {a, 2, 3} if f 1 = some a -/
def updateWith (f : α → Option α) (x : α) : Ordnode α → Ordnode α
| nil => nil
| _t@(node sz l y r) =>
match cmpLE x y with
| Ordering.lt => balanceR (updateWith f x l) y r
| Ordering.eq =>
match f y with
| none => glue l r
| some a => node sz l a r
| Ordering.gt => balanceL l y (updateWith f x r)