| 1 |
------------------------------------------------------------------------ |
| 2 |
-- The Agda standard library |
| 3 |
-- |
| 4 |
-- Types and functions which are used to keep track of height |
| 5 |
-- invariants in AVL Trees |
| 6 |
------------------------------------------------------------------------ |
| 7 |
|
| 8 |
{-# OPTIONS --cubical-compatible --safe #-} |
| 9 |
|
| 10 |
module Data.Tree.AVL.Height where |
| 11 |
|
| 12 |
open import Data.Nat.Base |
| 13 |
open import Data.Fin.Base using (Fin; zero; suc) |
| 14 |
|
| 15 |
ℕ₂ = Fin 2 |
| 16 |
pattern 0# = zero |
| 17 |
pattern 1# = suc zero |
| 18 |
pattern ## = suc (suc ()) |
| 19 |
|
| 20 |
-- Addition. |
| 21 |
|
| 22 |
infixl 6 _⊕_ |
| 23 |
|
| 24 |
_⊕_ : ℕ₂ → ℕ → ℕ |
| 25 |
0# ⊕ n = n |
| 26 |
1# ⊕ n = 1 + n |
| 27 |
|
| 28 |
-- pred[ i ⊕ n ] = pred (i ⊕ n). |
| 29 |
|
| 30 |
pred[_⊕_] : ℕ₂ → ℕ → ℕ |
| 31 |
pred[ i ⊕ zero ] = 0 |
| 32 |
pred[ i ⊕ suc n ] = i ⊕ n |
| 33 |
|
| 34 |
infix 4 _∼_⊔_ |
| 35 |
|
| 36 |
-- If i ∼ j ⊔ m, then the difference between i and j is at most 1, |
| 37 |
-- and the maximum of i and j is m. _∼_⊔_ is used to record the |
| 38 |
-- balance factor of the AVL trees, and also to ensure that the |
| 39 |
-- absolute value of the balance factor is never more than 1. |
| 40 |
|
| 41 |
data _∼_⊔_ : ℕ → ℕ → ℕ → Set where |
| 42 |
∼+ : ∀ {n} → n ∼ 1 + n ⊔ 1 + n |
| 43 |
∼0 : ∀ {n} → n ∼ n ⊔ n |
| 44 |
∼- : ∀ {n} → 1 + n ∼ n ⊔ 1 + n |
| 45 |
|
| 46 |
-- Some lemmas. |
| 47 |
|
| 48 |
max∼ : ∀ {i j m} → i ∼ j ⊔ m → m ∼ i ⊔ m |
| 49 |
max∼ ∼+ = ∼- |
| 50 |
max∼ ∼0 = ∼0 |
| 51 |
max∼ ∼- = ∼0 |
| 52 |
|
| 53 |
∼max : ∀ {i j m} → i ∼ j ⊔ m → j ∼ m ⊔ m |
| 54 |
∼max ∼+ = ∼0 |
| 55 |
∼max ∼0 = ∼0 |
| 56 |
∼max ∼- = ∼+ |