Lean4
/-- O(m * log(|m ∪ n| + 1)), m ≤ n. The union of two sets, preferring members of
`t₁` over those of `t₂` when equivalent elements are encountered.
union {1, 2} {2, 3} = {1, 2, 3}
union {1, 3} {2} = {1, 2, 3}
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
union {(1, 1)} {(0, 1), (1, 2)} = {(0, 1), (1, 1)} -/
def union : Ordnode α → Ordnode α → Ordnode α
| t₁, nil => t₁
| nil, t₂ => t₂
| t₁@(node s₁ l₁ x₁ r₁), t₂@(node s₂ _ x₂ _) =>
if s₂ = 1 then insert' x₂ t₁
else
if s₁ = 1 then insert x₁ t₂
else
let (l₂', r₂') := split x₁ t₂
link (union l₁ l₂') x₁ (union r₁ r₂')