| 1 |
------------------------------------------------------------------------ |
| 2 |
-- The Agda standard library |
| 3 |
-- |
| 4 |
-- W-types |
| 5 |
------------------------------------------------------------------------ |
| 6 |
|
| 7 |
{-# OPTIONS --cubical-compatible --safe #-} |
| 8 |
|
| 9 |
module Data.W where |
| 10 |
|
| 11 |
open import Level using (Level; _⊔_) |
| 12 |
open import Function.Base using (_$_; _∘_; const) |
| 13 |
open import Data.Product.Base using (_,_; -,_; proj₂) |
| 14 |
open import Data.Container.Core using (Container; ⟦_⟧; Shape; Position; _⇒_; ⟪_⟫) |
| 15 |
open import Data.Container.Relation.Unary.All using (□; all) |
| 16 |
open import Relation.Nullary.Negation using (¬_) |
| 17 |
open import Agda.Builtin.Equality using (_≡_; refl) |
| 18 |
|
| 19 |
private |
| 20 |
variable |
| 21 |
s p s₁ s₂ p₁ p₂ ℓ : Level |
| 22 |
C : Container s p |
| 23 |
C₁ : Container s₁ p₁ |
| 24 |
C₂ : Container s₂ p₂ |
| 25 |
|
| 26 |
-- The family of W-types. |
| 27 |
|
| 28 |
data W (C : Container s p) : Set (s ⊔ p) where |
| 29 |
sup : ⟦ C ⟧ (W C) → W C |
| 30 |
|
| 31 |
sup-injective₁ : ∀ {s t : Shape C} {f : Position C s → W C} {g} → |
| 32 |
sup (s , f) ≡ sup (t , g) → s ≡ t |
| 33 |
sup-injective₁ refl = refl |
| 34 |
|
| 35 |
-- See also Data.W.WithK.sup-injective₂. |
| 36 |
|
| 37 |
-- Projections. |
| 38 |
|
| 39 |
head : W C → Shape C |
| 40 |
head (sup (x , f)) = x |
| 41 |
|
| 42 |
tail : (x : W C) → Position C (head x) → W C |
| 43 |
tail (sup (x , f)) = f |
| 44 |
|
| 45 |
-- map |
| 46 |
|
| 47 |
map : (m : C₁ ⇒ C₂) → W C₁ → W C₂ |
| 48 |
map m (sup (x , f)) = sup (⟪ m ⟫ (x , λ p → map m (f p))) |
| 49 |
|
| 50 |
-- induction |
| 51 |
|
| 52 |
module _ (P : W C → Set ℓ) |
| 53 |
(alg : ∀ {t} → □ C P t → P (sup t)) where |
| 54 |
|
| 55 |
induction : (w : W C) → P w |
| 56 |
induction (sup (s , f)) = alg $ all (induction ∘ f) |
| 57 |
|
| 58 |
module _ {P : Set ℓ} (alg : ⟦ C ⟧ P → P) where |
| 59 |
|
| 60 |
foldr : W C → P |
| 61 |
foldr = induction (const P) (alg ∘ -,_ ∘ □.proof) |
| 62 |
|
| 63 |
-- If Position is always inhabited, then W_C is empty. |
| 64 |
|
| 65 |
inhabited⇒empty : (∀ s → Position C s) → ¬ W C |
| 66 |
inhabited⇒empty b = foldr ((_$ b _) ∘ proj₂) |